| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776 |
- //+------------------------------------------------------------------+
- //| localHedgingClientCopierMt5.mq5 |
- //| Copyright 2025, MetaQuotes Ltd. |
- //| https://www.mqldevelopment.com/ |
- //+------------------------------------------------------------------+
- #property copyright "Copyright 2025, MetaQuotes Ltd."
- #property link "https://www.mqldevelopment.com/"
- #property version "1.00"
- #define orderCount 2000
- #define count1 50
- #define testCounter 50
- #define MaxOrders 20000
- #define daysOfTradesToAdd 20
- #include <Trade\Trade.mqh>
- CTrade trade;
- //+------------------------------------------------------------------+
- //| Expert initialization function |
- //+------------------------------------------------------------------+
- struct historyTradesClientSide
- {
- ulong ticket;
- ulong magic;
- historyTradesClientSide()
- {
- ticket = -1;
- magic = 0;
- }
- };
- historyTradesClientSide historyTradeStore[MaxOrders];
- struct order
- {
- ulong ticket;
- double price;
- datetime opentime;
- string symbol;
- int ordertype;
- double lots;
- double stoploss;
- double takeprofit;
- double accountBalance;
- int contractSize;
- string comments;
- int magicNo;
- double closedPercentageOfTrade;
- order()
- {
- ticket =-1;
- closedPercentageOfTrade = 0;
- }
- };
- struct clientOrder
- {
- ulong ticket;
- double price;
- datetime opentime;
- string symbol;
- int ordertype;
- double lots;
- double stoploss;
- double takeprofit;
- ulong magic;
- string comments;
- double masterLot;
- clientOrder()
- {
- ticket=-1;
- price=-1;
- symbol=Symbol();
- ordertype=-1;
- lots=0;
- masterLot=0;
- stoploss=0;
- takeprofit=0;
- magic=0;
- comments="";
- }
- };
- clientOrder cod[orderCount];
- struct masterOrder
- {
- datetime opentime;
- string symbol;
- ulong ordertype;
- double price;
- double lots;
- double stoploss;
- double takeprofit;
- ulong ticket;
- int magic;
- double accountBalance;
- int contractSize;
- string comment;
- masterOrder()
- {
- ticket=-1;
- price=-1;
- symbol=Symbol();
- ordertype=-1;
- lots=0;
- stoploss=0;
- takeprofit=0;
- }
- };
- masterOrder mod1[orderCount];
- enum lot_option
- {
- fix, //Fixed Lot
- mul, //Multiplied Lot
- Balance, // Balance Base Multiplier
- slaveLotCal,
- };
- enum tradeCopy_type
- {
- buy,//Buy Only
- sell,//Sell Only
- buySell,//Buy and Sell
- };
- enum operation_code
- {
- Master, //Master
- Client, //Client
- };
- sinput string string_0 = "<><><><><><> General SETTINGS <><><><><><>"; //__
- input int slip = 5; // Master Order Variation in Pips
- input int sec = 10; // Master Order Expired After Seconds
- input tradeCopy_type tradeType = buySell; // Trades To Copy
- input lot_option lotoption = slaveLotCal; // Lot Option
- input double mult = 1.0; // Multiplier (for Client)
- input double fixed = 0.1; // Fixed Lot (for Client)
- input double Bmult = 1; // Balance Multiplier (for Client)
- input double recoveryAmount = 3000; // Recovery Amount (for Client Lot)
- input double maxDd = 8000; // Max DrawDown (for Client Lot)
- input string suffix = ""; // Suffix
- input string symbolExclude = ""; // Symbol to Exclude
- input string prefix = ""; // Prefix
- input string mappingSymbol = "GOLD,XAUUSD;bitcoin,BTCUSD"; // Mapping Pairs Inp,Out;Inp,Out
- // Heart Beat
- sinput string string_1 = "<><><><><><> HeartBeat Setting <><><><><><>"; //__
- input string clientServer = ""; // Master Server
- input string localApiKey = "U2FsdGVkX18vBY4H1uzQiZwuh8B++8VBtCGJ3yGr2XPII0qCodmfuhjssKu5oug1J4e97bkwPtDQLi4py1OODQ=="; // Local API Key
- input string localHB_req_link = "http://localhost/api/slastConnected"; // Request Link For LastConnected
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- //Global Variable
- int gmtDifference = 0;
- int filehandle;
- // Heart Beat
- long lastFileSize=0;
- datetime lastModified=0;
- bool contractChk = true;//Contract Checking
- bool doReversal = true; // Reverse Trades
- bool fileLastEmpty=false;
- long accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
- int counter=0,testCounterVar=0;
- order order_array[];
- datetime lastModified1=0;
- long lastFileSize1=0;
- bool fileHandlerIssue=false;
- operation_code mode1=Client; //Working code
- int OnInit()
- {
- //---
- accountNumber=AccountInfoInteger(ACCOUNT_LOGIN);
- EventSetMillisecondTimer(20);
- if(!ObjectFind(0,"mode") || ObjectGetString(0,"mode",OBJPROP_TEXT,0)!=EnumToString(mode1)+" Account")
- {
- ObjectDelete(0,"mode");
- ObjectCreate(0,"mode",OBJ_LABEL,0,0,0);
- ObjectSetInteger(0,"mode",OBJPROP_XDISTANCE,10);
- ObjectSetInteger(0,"mode",OBJPROP_YDISTANCE,25);
- ObjectSetInteger(0,"mode",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
- ObjectSetInteger(0,"mode",OBJPROP_ANCHOR,ANCHOR_RIGHT_UPPER);
- ObjectSetInteger(0,"mode",OBJPROP_COLOR,clrLightBlue);
- ObjectSetString(0,"mode",OBJPROP_TEXT,EnumToString(mode1)+" Account");
- ObjectSetInteger(0,"mode",OBJPROP_FONTSIZE,14);
- }
- gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
- Print("GMT Difference(sec): ",gmtDifference);
- mapHistory();
- //---
- return(INIT_SUCCEEDED);
- }
- //+------------------------------------------------------------------+
- //| Expert deinitialization function |
- //+------------------------------------------------------------------+
- void OnDeinit(const int reason)
- {
- //---
- EventKillTimer();
- ObjectsDeleteAll(0,0,-1);
- }
- //+------------------------------------------------------------------+
- //| Expert tick function |
- //+------------------------------------------------------------------+
- void OnTick()
- {
- //---
- }
- //+------------------------------------------------------------------+
- void OnTimer()
- {
- gmtDifference = (int)TimeCurrent() - (int)TimeGMT();
- read_history_file();
- readData();
- writeDataClientCof();
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void writeDataClientCof()
- {
- int fileHandleClientCof;
- if(PositionsTotal()==0 && OrdersTotal()==0 && !fileLastEmpty && TerminalInfoInteger(TERMINAL_CONNECTED))
- {
- fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
- if(fileHandleClientCof != INVALID_HANDLE)
- {
- Print("Writing file to empty");
- FileWrite(fileHandleClientCof, "");
- FileClose(fileHandleClientCof);
- fileLastEmpty = true;
- emptyStruct();
- }
- else
- {
- Print(" Client Cof File handler issue:", GetLastError());
- }
- }
- else
- {
- bool updationReq = checkOrderUpdate();
- if(updationReq || fileHandlerIssue)
- {
- Print(" ------------------------------- Client Cof Start ------------------------------------------ ");
- fileHandleClientCof = FileOpen("COF_client.csv", FILE_WRITE|FILE_CSV|FILE_COMMON);
- if(fileHandleClientCof != INVALID_HANDLE)
- {
- fileHandlerIssue = false;
- for(int i = PositionsTotal()-1; i >= 0; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- string time = TimeToString(PositionGetInteger(POSITION_TIME)-gmtDifference,TIME_DATE|TIME_SECONDS);
- string symbol = PositionGetString(POSITION_SYMBOL);
- double digits=getDoubleSymbolInfo(symbol,"digits");
- int symbolContractSize=(int)getDoubleSymbolInfo(symbol,"contract");
- ulong tempTicket = PositionGetInteger(POSITION_TICKET);
- if(suffix != "")
- symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
- if(prefix != "")
- StringReplace(symbol, prefix, "");
- long orderType = PositionGetInteger(POSITION_TYPE);
- double takeProfit = PositionGetDouble(POSITION_TP), stopLoss = PositionGetDouble(POSITION_SL);
- if(doReversal)
- {
- if(orderType == POSITION_TYPE_BUY)
- orderType = POSITION_TYPE_SELL;
- else
- if(orderType == POSITION_TYPE_SELL)
- orderType = POSITION_TYPE_BUY;
- takeProfit = PositionGetDouble(POSITION_SL);
- stopLoss = PositionGetDouble(POSITION_TP);
- }
- double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
- double currentLot = PositionGetDouble(POSITION_VOLUME);
- double totalLot = sumOfClosed + currentLot;
- double closedPercentage = 0.0;
- if(totalLot > 0.0)
- closedPercentage = (sumOfClosed / totalLot) * 100.0;
- Print(" Client Closed % = ", closedPercentage);
- string OrderToWrite = time+","+symbol+","+IntegerToString(orderType)+","+DoubleToString(PositionGetDouble(POSITION_PRICE_OPEN), (int)digits)+","+DoubleToString(PositionGetDouble(POSITION_VOLUME),2)+","+DoubleToString(stopLoss,(int) digits)+","+DoubleToString(takeProfit, (int) digits)+","+IntegerToString(PositionGetInteger(POSITION_TICKET))+","+IntegerToString(PositionGetInteger(POSITION_MAGIC))+","+(string)AccountInfoDouble(ACCOUNT_BALANCE)+","+DoubleToString(closedPercentage, 1)+","+(string)SymbolInfoDouble(PositionGetString(POSITION_SYMBOL),SYMBOL_TRADE_CONTRACT_SIZE)+PositionGetString(POSITION_COMMENT)+"\r\n";
- FileWrite(filehandle,OrderToWrite);
- }
- }
- for(int i = OrdersTotal()-1; i >= 0; i--)
- {
- ulong ticket = OrderGetTicket(i);
- if(OrderSelect(ticket))
- {
- string time = TimeToString(OrderGetInteger(ORDER_TIME_SETUP)-gmtDifference, TIME_DATE|TIME_SECONDS);
- string symbol = OrderGetString(ORDER_SYMBOL);
- double digits = getDoubleSymbolInfo(symbol,"digits");
- if(suffix != "")
- symbol = StringSubstr(symbol, 0, StringFind(symbol, suffix, 0));
- if(prefix != "")
- StringReplace(symbol, prefix, "");
- long orderType = OrderGetInteger(ORDER_TYPE);
- double takeProfit = OrderGetDouble(ORDER_TP);
- double stopLoss = OrderGetDouble(ORDER_SL);
- if(doReversal)
- {
- if(orderType == ORDER_TYPE_BUY_STOP)
- orderType = ORDER_TYPE_SELL_LIMIT;
- else
- if(orderType == ORDER_TYPE_SELL_STOP)
- orderType = ORDER_TYPE_BUY_LIMIT;
- else
- if(orderType == ORDER_TYPE_BUY_LIMIT)
- orderType = ORDER_TYPE_SELL_STOP;
- else
- if(orderType == ORDER_TYPE_SELL_LIMIT)
- orderType = ORDER_TYPE_BUY_STOP;
- takeProfit = OrderGetDouble(ORDER_SL);
- stopLoss = OrderGetDouble(ORDER_TP);
- }
- double closedPercentage = 0;
- string OrderToWrite =
- time + "," +
- symbol + "," +
- IntegerToString(orderType) + "," +
- DoubleToString(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits) + "," +
- DoubleToString(OrderGetDouble(ORDER_VOLUME_CURRENT),2) + "," +
- DoubleToString(stopLoss,(int)digits) + "," +
- DoubleToString(takeProfit,(int)digits) + "," +
- IntegerToString(OrderGetInteger(ORDER_TICKET)) + "," +
- IntegerToString(OrderGetInteger(ORDER_MAGIC)) + "," +
- (string)AccountInfoDouble(ACCOUNT_BALANCE) + "," +
- DoubleToString(closedPercentage) +","+
- (string)SymbolInfoDouble(OrderGetString(ORDER_SYMBOL), SYMBOL_TRADE_CONTRACT_SIZE) +
- OrderGetString(ORDER_COMMENT) + "\r\n";
- Print("Client Cof Writing Pending Order Block.");
- FileWrite(fileHandleClientCof, OrderToWrite);
- }
- }
- FileClose(fileHandleClientCof);
- fileLastEmpty = false;
- Print("Client Cof File Updated:", TimeCurrent());
- }
- else
- {
- Print("Client Cof File Handle Issue:", GetLastError());
- }
- Print(" ------------------------------- Client Cof End ------------------------------------------ ");
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool checkOrderUpdate()
- {
- bool updationRequired=false,currCheck=false;
- for(int i = PositionsTotal()-1 ; i >= 0 ; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- int orderIndex=-1;
- bool alreadyAdded=isOrderThere(ticket, orderIndex);
- if(!alreadyAdded)
- {
- currCheck=false;
- currCheck=addOrderMaster(ticket, "Market");
- if(!updationRequired)
- updationRequired=currCheck;
- }
- else
- {
- if(orderIndex!=-1)
- {
- currCheck=false;
- currCheck=IsOrderChanged(PositionGetInteger(POSITION_TICKET),orderIndex, "Market");
- if(!updationRequired)
- {
- updationRequired=currCheck;
- }
- }
- }
- }
- }
- for(int i = OrdersTotal()-1 ; i >= 0 ; i--)
- {
- ulong ticket = OrderGetTicket(i);
- if(OrderSelect(ticket))
- {
- if(OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_BUY && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_SELL && OrderGetInteger(ORDER_TYPE) != ORDER_TYPE_CLOSE_BY)
- {
- int orderIndex=-1;
- bool alreadyAdded=isOrderThere(ticket, orderIndex);
- if(!alreadyAdded)
- {
- Print("Inside pending Adding to master order: ",ticket," type: ",OrderGetInteger(ORDER_TYPE)," ",OrdersTotal()," ",ORDER_TYPE_CLOSE_BY);
- currCheck=false;
- currCheck=addOrderMaster(ticket, "Pending");
- if(!updationRequired)
- updationRequired=currCheck;
- }
- else
- {
- if(orderIndex!=-1)
- {
- currCheck=false;
- currCheck=IsOrderChanged(OrderGetInteger(ORDER_TICKET), orderIndex, "Pending");
- if(!updationRequired)
- {
- updationRequired=currCheck;
- }
- }
- }
- }
- }
- }
- for(int i=0; i<ArraySize(mod1); i++)
- {
- bool isPresent=false;
- if(mod1[i].ticket !=-1)
- {
- for(int j = PositionsTotal()-1; j>=0; j--)
- {
- ulong ticket = PositionGetTicket(j);
- if(PositionSelectByTicket(ticket))
- {
- if(ticket==mod1[i].ticket)
- {
- isPresent=true;
- break;
- }
- }
- }
- // Pending Order
- for(int j = OrdersTotal()-1; j>=0; j--)
- {
- ulong ticket = OrderGetTicket(j);
- if(OrderSelect(ticket))
- {
- if(ticket==mod1[i].ticket)
- {
- isPresent=true;
- break;
- }
- }
- }
- if(!isPresent)
- {
- Print("Ticket is closed so removed from struct: ",mod1[i].ticket);
- mod1[i].ticket=-1;
- mod1[i].price=-1;
- mod1[i].symbol="";
- mod1[i].ordertype=-1;
- mod1[i].lots=0;
- mod1[i].stoploss=0;
- mod1[i].takeprofit=0;
- currCheck=true;
- //currCheck=clearStructIndex(mod1[i].ticket);
- if(!updationRequired)
- updationRequired=currCheck;
- }
- }
- }
- return updationRequired;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool IsOrderChanged(ulong orderTicket, int index, string calledBy)
- {
- if(mod1[index].ticket!=-1)
- {
- if(calledBy == "Market")
- {
- if(PositionSelectByTicket(orderTicket))
- {
- //Digits
- double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
- double tp=NormalizeDouble(PositionGetDouble(POSITION_TP), (int)digits),
- sl=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits),
- lot=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
- if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=PositionGetInteger(POSITION_TYPE) || mod1[index].price != PositionGetDouble(POSITION_PRICE_OPEN))
- {
- Print(" Inside IsOrderChanged() ",mod1[index].lots," lot: ",lot," calledBy: ",calledBy," mod1 ticket ",mod1[index].ticket," orderTicket: ",orderTicket);
- // Time
- datetime time = (datetime)(PositionGetInteger(POSITION_TIME) - gmtDifference);
- mod1[index].opentime=time;
- mod1[index].lots=lot;
- mod1[index].stoploss=sl;
- mod1[index].takeprofit=tp;
- mod1[index].comment=PositionGetString(POSITION_COMMENT);
- mod1[index].ordertype=PositionGetInteger(POSITION_TYPE);
- mod1[index].price=PositionGetDouble(POSITION_PRICE_OPEN);
- return true;
- }
- }
- }
- if(calledBy == "Pending")
- {
- if(OrderSelect(orderTicket))
- {
- double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
- double tp=NormalizeDouble(OrderGetDouble(ORDER_TP), (int)digits),
- sl=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits),
- lot=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
- if(mod1[index].takeprofit!=tp || mod1[index].stoploss != sl || mod1[index].lots!=lot || mod1[index].ordertype!=OrderGetInteger(ORDER_TYPE) || mod1[index].price != OrderGetDouble(ORDER_PRICE_OPEN))
- {
- //time
- datetime time = (datetime)(OrderGetDouble(ORDER_PRICE_OPEN) - gmtDifference);
- mod1[index].opentime=time;
- mod1[index].lots=lot;
- mod1[index].stoploss=sl;
- mod1[index].takeprofit=tp;
- mod1[index].comment=OrderGetString(ORDER_COMMENT);
- mod1[index].ordertype=OrderGetInteger(ORDER_TYPE);
- mod1[index].price=OrderGetDouble(ORDER_PRICE_OPEN);
- return true;
- }
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool addOrderMaster(ulong ticket, string calledBy)
- {
- for(int i=0; i<ArraySize(mod1); i++)
- {
- if(mod1[i].ticket==-1)
- {
- if(calledBy == "Market")
- {
- //ulong ticket = PositionGetTicket(orderTicket);
- if(PositionSelectByTicket(ticket))
- {
- //Symbol Updation
- string symbol=PositionGetString(POSITION_SYMBOL);
- if(suffix!="")
- symbol = StringSubstr(symbol,0,StringFind(PositionGetString(POSITION_SYMBOL),suffix,0));
- if(prefix!="")
- StringReplace(symbol,prefix,"");
- //Digits
- double digits=getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL),"digits");
- //time
- datetime time = (datetime)(PositionGetInteger(POSITION_TIME)-gmtDifference);
- mod1[i].opentime=time;
- mod1[i].symbol=symbol;
- mod1[i].ordertype=PositionGetInteger(POSITION_TYPE);
- mod1[i].price=NormalizeDouble(PositionGetDouble(POSITION_PRICE_OPEN),(int)digits);
- mod1[i].lots=NormalizeDouble(PositionGetDouble(POSITION_VOLUME),2);
- mod1[i].stoploss=NormalizeDouble(PositionGetDouble(POSITION_SL),(int)digits);
- mod1[i].takeprofit=NormalizeDouble(PositionGetDouble(POSITION_TP),(int)digits);
- mod1[i].ticket=PositionGetInteger(POSITION_TICKET);
- mod1[i].magic=(int)PositionGetInteger(POSITION_MAGIC);
- mod1[i].comment=PositionGetString(POSITION_COMMENT);
- Print("Ticket:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
- return true;
- }
- }
- if(calledBy == "Pending")
- {
- if(OrderSelect(ticket))
- {
- string symbol = OrderGetString(ORDER_SYMBOL);
- if(suffix!="")
- symbol = StringSubstr(symbol,0,StringFind(OrderGetString(ORDER_SYMBOL),suffix,0));
- if(prefix!="")
- StringReplace(symbol,prefix,"");
- //Digits
- double digits=getDoubleSymbolInfo(OrderGetString(ORDER_SYMBOL),"digits");
- //time
- datetime time = (datetime)(OrderGetInteger(ORDER_TIME_SETUP) - gmtDifference);
- mod1[i].opentime=time;
- mod1[i].symbol=symbol;
- mod1[i].ordertype=OrderGetInteger(ORDER_TYPE);
- mod1[i].price=NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN),(int)digits);
- mod1[i].lots=NormalizeDouble(OrderGetDouble(ORDER_VOLUME_CURRENT),2);
- mod1[i].stoploss=NormalizeDouble(OrderGetDouble(ORDER_SL),(int)digits);
- mod1[i].takeprofit=NormalizeDouble(OrderGetDouble(ORDER_TP),(int)digits);
- mod1[i].ticket=OrderGetInteger(ORDER_TICKET);
- mod1[i].magic=(int)OrderGetInteger(ORDER_MAGIC);
- mod1[i].comment=OrderGetString(ORDER_COMMENT);
- Print("Ticket: ",OrderGetInteger(ORDER_TICKET)," stored in index by pending order:",i);
- return true;
- }
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void readData()
- {
- if(EnumToString(mode1)=="Client")
- {
- filehandle=FileOpen("COF.csv",FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
- if(filehandle!=INVALID_HANDLE)
- {
- datetime lastFileModified=(datetime)FileGetInteger(filehandle,FILE_MODIFY_DATE);
- long fileSize=FileGetInteger(filehandle,FILE_SIZE);
- int a= 0;
- if(lastModified==lastFileModified && fileSize==lastFileSize) // lastModified==lastFileModified && fileSize==lastFileSize
- {
- FileClose(filehandle);
- if(counter>=count1 && TerminalInfoInteger(TERMINAL_CONNECTED))
- {
- if(testCounterVar==testCounter)
- {
- testCounterVar=0;
- }
- adminHeartBeat();
- counter=0;
- }
- counter++;
- testCounterVar++;
- }
- else
- {
- clearOrderArray();
- while(!FileIsEnding(filehandle))
- {
- string OrderToRead = FileReadString(filehandle);
- string Order_specs [];
- StringSplit(OrderToRead,StringGetCharacter(",",0),Order_specs);
- Print("Array Size: ", ArraySize(Order_specs));
- if(ArraySize(Order_specs) == 12 || ArraySize(Order_specs) == 13)
- {
- string symbol = getSymbol(Order_specs[1]);//prefix+Order_specs[1]+suffix;
- int orderType=StringToInteger(Order_specs[2]);
- if(StringFind(symbol,symbolExclude,0) < 0 &&
- (((orderType==POSITION_TYPE_BUY||orderType==ORDER_TYPE_BUY_STOP ||orderType==ORDER_TYPE_SELL_STOP)&& (tradeType==0||tradeType==2)) ||
- ((orderType==POSITION_TYPE_SELL||orderType==ORDER_TYPE_BUY_LIMIT ||orderType==ORDER_TYPE_SELL_LIMIT)&& (tradeType==1||tradeType==2)))
- )
- {
- order_array[ArraySize(order_array)-1].symbol = symbol;
- order_array[ArraySize(order_array)-1].opentime = StringToTime(Order_specs[0]);
- order_array[ArraySize(order_array)-1].price = StringToDouble(Order_specs[3]);
- order_array[ArraySize(order_array)-1].ordertype = StringToInteger(Order_specs[2]);
- order_array[ArraySize(order_array)-1].lots = StringToDouble(Order_specs[4]);
- order_array[ArraySize(order_array)-1].stoploss = StringToDouble(Order_specs[5]);
- order_array[ArraySize(order_array)-1].takeprofit = StringToDouble(Order_specs[6]);
- order_array[ArraySize(order_array)-1].ticket = StringToInteger(Order_specs[7]);
- //Saving master order ticket to order magic number
- order_array[ArraySize(order_array)-1].magicNo = StringToInteger(Order_specs[7]);
- order_array[ArraySize(order_array)-1].accountBalance=StringToDouble(Order_specs[9]);
- order_array[ArraySize(order_array)-1].closedPercentageOfTrade = StringToDouble(Order_specs[10]);
- order_array[ArraySize(order_array)-1].contractSize=StringToInteger(Order_specs[11]);
- if(ArraySize(Order_specs) == 13)
- order_array[ArraySize(order_array)-1].comments=Order_specs[12];
- else
- order_array[ArraySize(order_array)-1].comments="";
- if(ArraySize(Order_specs) == 13)
- {
- StringReplace(Order_specs[12],"from #","");
- StringReplace(Order_specs[12]," ","");
- Print(" Order_specs[12] ",Order_specs[12]," order_array[ArraySize(order_array)-1].ticket ",order_array[ArraySize(order_array)-1].ticket);
- for(int l=0; l<orderCount; l++)
- {
- if(cod[l].magic == int(Order_specs[12]))
- {
- cod[l].magic = order_array[ArraySize(order_array)-1].ticket;
- }
- }
- }
- Print(" Symbol: ", order_array[ArraySize(order_array)-1].symbol,
- " Open Price: ", order_array[ArraySize(order_array)-1].price,
- " Lot: ", order_array[ArraySize(order_array)-1].lots,
- " Open time: ", order_array[ArraySize(order_array)-1].opentime,
- " Closed %: ", order_array[ArraySize(order_array)-1].closedPercentageOfTrade);
- ArrayResize(order_array,ArraySize(order_array)+1);
- addToMarketWatch(symbol);
- }
- }
- }
- lastModified=lastFileModified;
- lastFileSize=fileSize;
- FileClose(filehandle);
- }
- int arraySize=ArraySize(order_array);
- if(ArraySize(order_array) == 1) //
- {
- if(PositionsTotal() > 0)
- {
- for(int i=PositionsTotal()-1; i>=0; i--)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(history_ticket_present(PositionGetInteger(POSITION_MAGIC)))
- if(!trade.PositionClose(ticket))
- {
- Print(" Order Close Error on No Master Trade: "+IntegerToString(GetLastError()));
- }
- else
- Print(" ------------- Order Close by empty array ------------------ ");
- }
- }
- }
- if(OrdersTotal() > 0)
- {
- for(int i=OrdersTotal()-1; i>=0; i--)
- {
- ulong ticket = OrderGetTicket(i);
- if(OrderSelect(ticket))
- {
- if(history_ticket_present(OrderGetInteger(ORDER_MAGIC)))
- if(!trade.OrderDelete(ticket))
- {
- Print(" Error in Deleting Pending Order (Empty Array) : "+IntegerToString(GetLastError()));
- }
- else
- Print("Order Close by empty array (Empty Array)");
- }
- }
- }
- deleteAllArray();
- }
- else
- {
- for(int i=0; i<ArraySize(order_array); i++)
- {
- //Print(" ------------------------------------------ Ticket: ", order_array[ArraySize(order_array)-1].ticket, " Magic Number: ", order_array[ArraySize(order_array)-1].magicNo, " Array Size: ", ArraySize(order_array), " Index: ", i);
- int trade_taken = 2;
- int partialCloseOrderPosition=-1;
- double percentageToClose = 0;
- double closedPercentage = 0.0;
- double currentLot = 0.0;
- double totalLot = 0;
- for(int j=0; j<orderCount; j++)
- {
- //if(OrderSelect(cod[j].ticket,SELECT_BY_POS))
- if(cod[j].ticket!=-1)
- {
- if(cod[j].magic==order_array[i].ticket)
- {
- trade_taken = 0;
- }
- if(PositionSelectByTicket(cod[j].ticket))
- {
- double sumOfClosed = dealOutLotsCheck(0, PositionGetInteger(POSITION_TICKET));
- currentLot = PositionGetDouble(POSITION_VOLUME);
- totalLot = sumOfClosed + currentLot;
- if(totalLot > 0.0)
- closedPercentage = NormalizeDouble((sumOfClosed / totalLot) * 100.0, 1);
- }
- //Print(" Magic: ", cod[j].magic, " Ticket: ", order_array[i].ticket, " Master Lot: ", cod[j].masterLot, " Client Lot: ", order_array[i].lots);
- if(cod[j].magic==order_array[i].ticket)
- {
- if(closedPercentage < order_array[i].closedPercentageOfTrade)
- {
- percentageToClose = MathAbs(order_array[i].closedPercentageOfTrade - closedPercentage);
- trade_taken=1;
- partialCloseOrderPosition=j;
- }
- }
- }
- }
- if(order_array[i].ticket != -1)
- {
- if(trade_taken==1)
- {
- //current order need to close partially
- if(partialCloseOrderPosition!=-1)
- {
- bool isOrderClose=false;
- int roundDigit=0;
- double step=SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_STEP);
- while(step<1)
- {
- roundDigit++;
- step=step*10;
- }
- double lotClosePer = NormalizeDouble((totalLot * percentageToClose) / 100, roundDigit);
- if(percentageToClose > 0 && lotClosePer > SymbolInfoDouble(cod[partialCloseOrderPosition].symbol,SYMBOL_VOLUME_MIN))
- {
- if(!trade.PositionClosePartial(cod[partialCloseOrderPosition].ticket, lotClosePer))
- {
- Print("Partial order did not close:",cod[partialCloseOrderPosition].ticket, " Lot To Close is: ", lotClosePer);
- }
- else
- {
- isOrderClose=true;
- Print("Order Partial Close. currentLot Was =", currentLot,
- " Percentage to close = ", percentageToClose,
- " Lot I am Going To close = ", lotClosePer);
- }
- }
- }
- }
- else
- if(trade_taken == 2)
- {
- int diff1=((int)TimeCurrent()-(int)order_array[i].opentime)-gmtDifference;// ,diff2=TimeSeconds(TimeCurrent()-order_array[i].opentime);
- if(diff1 <= sec)
- {
- Print("Symbol: ",order_array[i].opentime," ",diff1," <= ",sec);
- trade.SetExpertMagicNumber(IntegerToString(order_array[i].ticket));
- trade.SetDeviationInPoints(10);
- trade.SetTypeFilling(ORDER_FILLING_IOC);
- trade.LogLevel(LOG_LEVEL_ALL);
- trade.SetAsyncMode(false);
- if(order_array[i].ordertype == ORDER_TYPE_BUY)
- {
- double tempSlip=MathAbs(order_array[i].price- SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT);
- if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
- {
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- double Stoploss=0.0;
- double ask=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_ASK),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
- if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_BUY,lotsize,ask,order_array[i].stoploss,order_array[i].takeprofit,""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
- {
- Print(" Buy Order Ticket:",trade.ResultOrder()," Stored!!!");
- }
- else
- {
- //Print("Order Ticket is not stotred: ",trade.ResultOrder()," Error is: ", GetLastError());
- }
- }
- else
- {
- Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
- }
- }
- }
- if(order_array[i].ordertype == ORDER_TYPE_SELL)
- {
- if((MathAbs(order_array[i].price-SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID))/SymbolInfoDouble(order_array[i].symbol,SYMBOL_POINT)) <= slip*10)
- {
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- double Stoploss=0.0;
- double bid=NormalizeDouble(SymbolInfoDouble(order_array[i].symbol,SYMBOL_BID),(int)SymbolInfoInteger(order_array[i].symbol,SYMBOL_DIGITS));
- if(trade.PositionOpen(order_array[i].symbol,ORDER_TYPE_SELL,lotsize,bid,order_array[i].stoploss,order_array[i].takeprofit,""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Market"))
- {
- Print(" Sell Order Ticket:",trade.ResultOrder()," Stored!!!");
- }
- }
- else
- {
- Print("Copy Buy Order Send Error: "+IntegerToString(GetLastError()));
- }
- }
- }
- if(order_array[i].ordertype == ORDER_TYPE_BUY_STOP)
- {
- // Not Checking Slippage
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- if(trade.BuyStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
- {
- Print("Order Ticket Buy Stop:",trade.ResultOrder()," Stored!!!");
- }
- }
- else
- {
- Print("Error in Order Buy Stop Order: "+Symbol()+" ",GetLastError());
- }
- }
- if(order_array[i].ordertype == ORDER_TYPE_SELL_STOP)
- {
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- if(trade.SellStop(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
- {
- Print("Order Ticket Sell Stop:",trade.ResultOrder()," Stored!!!");
- }
- }
- else
- {
- Print("Error in Order Sell Stop Order: "+Symbol()+" ",GetLastError());
- }
- }
- if(order_array[i].ordertype == ORDER_TYPE_BUY_LIMIT)
- {
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- if(trade.BuyLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
- {
- Print("Order Ticket Buy Limit:",trade.ResultOrder()," Stored!!!");
- }
- }
- else
- {
- Print("Error in Order Buy Limit: "+Symbol()+" ",GetLastError());
- }
- }
- if(order_array[i].ordertype == ORDER_TYPE_SELL_LIMIT)
- {
- double lotsize = getLotSize(order_array[i].symbol, order_array[i].accountBalance, order_array[i].lots, order_array[i].contractSize);
- if(trade.SellLimit(lotsize, order_array[i].price, order_array[i].symbol, order_array[i].stoploss, order_array[i].takeprofit, 0, 0, ""))
- {
- if(addOrderMaster(trade.ResultOrder(),order_array[i].ticket,order_array[i].lots, "Pending"))
- {
- Print("Order Ticket Sell Limit: ",trade.ResultOrder()," Stored!!! ", " Tp: ", order_array[i].takeprofit, " Sl: ", order_array[i].stoploss);
- }
- }
- else
- {
- Print("Error in Order Sell Limit: "+Symbol()+" ",GetLastError());
- }
- }
- }
- }
- }
- }
- for(int i=0; i<orderCount; i++)
- {
- bool trade_close = true;
- if(PositionSelectByTicket(cod[i].ticket))
- {
- for(int j=0; j<ArraySize(order_array); j++)
- {
- if(cod[i].magic == (order_array[j].ticket))
- {
- int digitss = getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
- trade_close = false;
- //Print("TP/SL | norm cod TP=",NormalizeDouble(cod[i].takeprofit,digitss),
- // " norm order TP=",NormalizeDouble(order_array[j].takeprofit,digitss),
- // " | norm cod SL=",NormalizeDouble(cod[i].stoploss,digitss),
- // " norm order SL=",NormalizeDouble(order_array[j].stoploss,digitss));
- if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
- {
- if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(PositionGetDouble(POSITION_TP), digitss))
- {
- Print(" Client Position Tp Was Manually Modified. ");
- cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
- }
- }
- if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
- {
- if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(PositionGetDouble(POSITION_SL), digitss))
- {
- Print(" Client Position SL Was Manually Modified. ");
- cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
- }
- }
- if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss) || NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
- {
- if(trade.PositionModify(PositionGetInteger(POSITION_TICKET),order_array[j].stoploss,order_array[j].takeprofit))
- {
- Print("Order modified ticket:",PositionGetInteger(POSITION_TICKET));
- cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
- cod[i].stoploss=NormalizeDouble(order_array[j].stoploss, digitss);
- }
- else
- {
- //ExpertRemove();
- Print("Order not modified error:",GetLastError());
- }
- }
- }
- }
- if(trade_close == true)
- {
- if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_BUY)
- {
- if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
- {
- Print("Buy Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
- }
- else
- {
- Print("Order close by no master copy of trade");
- cod[i].ticket=-1;
- }
- }
- if(PositionGetInteger(POSITION_TYPE)== ORDER_TYPE_SELL)
- {
- if(!trade.PositionClose(PositionGetInteger(POSITION_TICKET)))
- {
- Print("Sell Order Close Error on Master Trade Close: "+IntegerToString(GetLastError()));
- }
- else
- {
- Print("Order close by no master copy of trade");
- cod[i].ticket=-1;
- }
- }
- }
- }
- if(OrderSelect(cod[i].ticket))
- {
- for(int j=0; j<ArraySize(order_array); j++)
- {
- if(cod[i].magic == (order_array[j].ticket))
- {
- trade_close = false;
- int digitss = (int)getDoubleSymbolInfo(PositionGetString(POSITION_SYMBOL), "digits");
- if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss))
- {
- if(NormalizeDouble(order_array[j].takeprofit, digitss) == NormalizeDouble(OrderGetDouble(ORDER_TP), digitss))
- {
- Print(" Pending Master Position Tp Was Manually Modified. ");
- cod[i].takeprofit=NormalizeDouble(order_array[j].takeprofit, digitss);
- }
- }
- if(NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss))
- {
- if(NormalizeDouble(order_array[j].stoploss, digitss) == NormalizeDouble(OrderGetDouble(ORDER_SL), digitss))
- {
- Print(" Pending Master Position SL Was Manually Modified. ");
- cod[i].stoploss = NormalizeDouble(order_array[j].stoploss, digitss);
- }
- }
- if(NormalizeDouble(cod[i].price, digitss) != NormalizeDouble(order_array[j].price, digitss))
- {
- if(NormalizeDouble(order_array[j].price, digitss) == NormalizeDouble(OrderGetDouble(ORDER_PRICE_OPEN), digitss))
- {
- Print(" Pending Master Position Price Was Manually Modified. ");
- cod[i].price = NormalizeDouble(order_array[j].price, digitss);
- }
- }
- // if(OrderGetDouble(ORDER_TP)!=order_array[j].takeprofit || OrderGetDouble(ORDER_SL)!=order_array[j].stoploss || OrderGetDouble(ORDER_PRICE_OPEN)!=order_array[j].price)
- if(NormalizeDouble(cod[i].takeprofit, digitss) != NormalizeDouble(order_array[j].takeprofit, digitss) || NormalizeDouble(cod[i].stoploss, digitss) != NormalizeDouble(order_array[j].stoploss, digitss) || NormalizeDouble(cod[i].price, digitss) != NormalizeDouble(order_array[j].price, digitss))
- {
- if(trade.OrderModify(OrderGetInteger(ORDER_TICKET),order_array[j].price,order_array[j].stoploss,order_array[j].takeprofit, 0, 0, 0))
- {
- Print("Pending Order modified ticket:",PositionGetInteger(POSITION_TICKET));
- cod[i].takeprofit=order_array[j].takeprofit;
- cod[i].stoploss=order_array[j].stoploss;
- cod[i].price = order_array[j].price;
- }
- else
- {
- Print("Order not modified error:",GetLastError());
- }
- }
- }
- }
- if(trade_close == true)
- {
- if(OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_BUY_STOP || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_SELL_STOP || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_BUY_LIMIT || OrderGetInteger(ORDER_TYPE)== ORDER_TYPE_SELL_LIMIT)
- {
- if(!trade.OrderDelete(OrderGetInteger(ORDER_TICKET)))
- {
- Print("Error in Deleting Pending Order: "+IntegerToString(GetLastError()));
- }
- else
- {
- Print("Pending Order Deleted. Ticket is: ", cod[i].ticket);
- cod[i].ticket=-1;
- }
- }
- }
- }
- }
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void print()
- {
- for(int i=0; i<orderCount; i++)
- {
- if(cod[i].ticket!=-1)
- {
- Print("Ticket : ",cod[i].ticket," OPen price: ",cod[i].price, " Type: ",cod[i].ordertype);
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool isOrderThere(ulong ticket,int &index)
- {
- for(int i=0; i<ArraySize(mod1); i++)
- {
- if(ticket != -1)
- {
- if(mod1[i].ticket==ticket)
- {
- index=i;
- return true;
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void emptyStruct()
- {
- for(int i = 0 ; i < orderCount ; i++)
- {
- if(mod1[i].ticket != -1)
- {
- mod1[i].ticket=-1;
- mod1[i].magic=0;
- mod1[i].price=-1;
- mod1[i].symbol="";
- mod1[i].ordertype=-1;
- mod1[i].lots=0;
- mod1[i].stoploss=0;
- mod1[i].takeprofit=0;
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void deleteAllArray()
- {
- for(int i=0; i<orderCount; i++)
- {
- if(cod[i].ticket!=-1)
- {
- cod[i].ticket=-1;
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- double dealOutLotsCheck(datetime cutOffTimeIs, ulong positionId)
- {
- double sumOfLots = 0.0;
- if(HistorySelect(cutOffTimeIs,LONG_MAX))
- {
- int totalDeals = HistoryDealsTotal();
- for(int i = 0; i < totalDeals; i++)
- {
- ulong dealTicket = HistoryDealGetTicket(i);
- ulong dealPositionID = (ulong)HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
- if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT
- && dealPositionID == positionId)
- {
- sumOfLots += HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
- }
- }
- }
- return sumOfLots;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool addOrderMaster(ulong ticket,ulong magic,double lot, string calledBy)
- {
- Print("in addOrderMaster: ", ticket);
- bool notFoundPosition=false;//Use to look in to the order loop in case order isn't converted
- if(OrderSelect(ticket))
- {
- Print("Inside order selection:");
- Print("Order State:",(ENUM_ORDER_STATE)OrderGetInteger(ORDER_STATE));
- Print("Order Time done:",(datetime)OrderGetInteger(ORDER_TIME_DONE));
- Print("Order Type:",(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE));
- }
- else
- if(HistoryOrderSelect(ticket))
- {
- Print("Inside history order selection:");
- Print("Order State:",(ENUM_ORDER_STATE)HistoryOrderGetInteger(ticket,ORDER_STATE));
- Print("Order Time done:",(datetime)HistoryOrderGetInteger(ticket,ORDER_TIME_DONE));
- Print("Order Type:",(ENUM_ORDER_TYPE)HistoryOrderGetInteger(ticket,ORDER_TYPE));
- }
- else
- {
- PrintFormat("OrderSelect(%I64u) failed. Error %d", ticket, GetLastError());
- }
- for(int i=0; i<orderCount; i++)
- {
- if(cod[i].ticket==-1)
- {
- if(calledBy == "Market")
- {
- if(PositionSelectByTicket(ticket))
- {
- cod[i].ticket=PositionGetInteger(POSITION_TICKET);
- cod[i].price=PositionGetDouble(POSITION_PRICE_OPEN);
- cod[i].symbol=PositionGetString(POSITION_SYMBOL);
- cod[i].ordertype=PositionGetInteger(POSITION_TYPE);
- cod[i].lots=PositionGetDouble(POSITION_VOLUME);
- cod[i].stoploss=PositionGetDouble(POSITION_SL);
- cod[i].takeprofit=PositionGetDouble(POSITION_TP);
- cod[i].magic=PositionGetInteger(POSITION_MAGIC);
- cod[i].comments=PositionGetString(POSITION_COMMENT);
- cod[i].masterLot = lot;
- Print("Ticket stored in master:",PositionGetInteger(POSITION_TICKET)," stored in index:",i);
- Print("========== CLIENT ORDER STORED ==========");
- Print(" index=", i,
- " | master_magic=", cod[i].magic,
- " | client_ticket=", cod[i].ticket,
- " | symbol=", cod[i].symbol,
- " | order_type=", cod[i].ordertype,
- " | open_price=", DoubleToString(cod[i].price, _Digits),
- " | lots=", DoubleToString(cod[i].lots, 2),
- " | master_lot=", DoubleToString(cod[i].masterLot, 2),
- " | sl=", DoubleToString(cod[i].stoploss, _Digits),
- " | tp=", DoubleToString(cod[i].takeprofit, _Digits),
- " | comment=", cod[i].comments);
- Print("========================================");
- return true;
- }
- else
- {
- Print("Ticket:",ticket," not found in the position list");
- notFoundPosition=true;
- }
- }
- if(calledBy == "Pending" || notFoundPosition)
- {
- if(OrderSelect(ticket))
- {
- cod[i].ticket=OrderGetInteger(ORDER_TICKET);
- cod[i].price=OrderGetDouble(ORDER_PRICE_OPEN);
- cod[i].symbol=OrderGetString(ORDER_SYMBOL);
- cod[i].ordertype=OrderGetInteger(ORDER_TYPE);
- cod[i].lots=OrderGetDouble(ORDER_VOLUME_CURRENT);
- cod[i].stoploss=OrderGetDouble(ORDER_SL);
- cod[i].takeprofit=OrderGetDouble(ORDER_TP);
- cod[i].magic=OrderGetInteger(ORDER_MAGIC);
- cod[i].comments=OrderGetString(ORDER_COMMENT);
- cod[i].masterLot = lot;
- Print("Pending Order Ticket in master:",OrderGetInteger(ORDER_TICKET)," stored in index:",i);
- return true;
- }
- else
- {
- Print("Ticket:",ticket," not found in the order list");
- }
- }
- }
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- double getDoubleSymbolInfo(string symbol,string info)
- {
- long digits=8;
- //Symbol without the suffix and prefix
- string updatedSymbol=symbol;
- if(suffix!="")
- updatedSymbol = StringSubstr(updatedSymbol,0,StringFind(updatedSymbol,suffix,0));
- if(prefix!="")
- StringReplace(updatedSymbol,prefix,"");
- //Digits calculation could be used in other calculations
- digits = SymbolInfoInteger(symbol,SYMBOL_DIGITS);
- if(digits==0)
- {
- digits=SymbolInfoInteger(updatedSymbol,SYMBOL_DIGITS);
- if(digits==0)
- digits=8;
- }
- if(info=="digits")
- {
- return (double)digits;
- }
- else
- if(info=="point" || info=="points")
- {
- double points=SymbolInfoDouble(symbol, SYMBOL_POINT);
- if(points==0)
- {
- points=SymbolInfoDouble(updatedSymbol,SYMBOL_POINT);
- if(points==0)
- points=0.00001;
- }
- return points;
- }
- else
- if(info=="ask")
- {
- double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
- if(ask==0)
- {
- ask=SymbolInfoDouble(updatedSymbol,SYMBOL_ASK);
- if(ask==0)
- ask=0.00001;
- }
- return NormalizeDouble(ask,(int)digits);
- }
- else
- if(info=="bid")
- {
- double bid=SymbolInfoDouble(symbol, SYMBOL_BID);
- if(bid==0)
- {
- bid=SymbolInfoDouble(updatedSymbol,SYMBOL_BID);
- if(bid==0)
- bid=0.00001;
- }
- return NormalizeDouble(bid,(int)digits);
- }
- else
- if(info=="contract"||info=="contractSize")
- {
- double contract=SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE);
- if(contract==0)
- {
- contract=SymbolInfoDouble(updatedSymbol,SYMBOL_TRADE_CONTRACT_SIZE);
- }
- return contract;
- }
- else
- if(info=="lotStep")
- {
- double step=SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
- if(step==0)
- {
- step=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_STEP);
- }
- return step;
- }
- else
- if(info=="minLot")
- {
- double minLot=SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
- if(minLot==0)
- {
- minLot = SymbolInfoDouble(updatedSymbol, SYMBOL_VOLUME_MIN);
- }
- return minLot;
- }
- else
- if(info=="maxLot")
- {
- double maxLot=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX);
- if(maxLot==0)
- {
- maxLot=SymbolInfoDouble(updatedSymbol,SYMBOL_VOLUME_MAX);
- }
- return maxLot;
- }
- return 0;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- string getSymbol(string symbol)
- {
- if(mappingSymbol!="")
- {
- string symbollist[];
- StringSplit(mappingSymbol,';',symbollist);
- for(int i=0; i<ArraySize(symbollist); i++)
- {
- string symbolPairs[];
- StringSplit(symbollist[i],',',symbolPairs);
- if(ArraySize(symbolPairs)==2)
- {
- if(symbol==symbolPairs[0])
- return symbolPairs[1];
- }
- }
- }
- else
- {
- return prefix+symbol+suffix;
- }
- return prefix+symbol+suffix;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- double getLotSize(string symbol,double masterAccountBalance,double masterLot,int masterContractSize)
- {
- double lotsize = fixed;
- Print("------> Symbol:",symbol," master Account balance:",masterAccountBalance," master lot:",masterLot," master Contract:",masterContractSize);
- if(lotoption == mul)
- {
- lotsize = NormalizeDouble(masterLot*mult,2);
- }
- else
- if(lotoption == Balance)
- {
- lotsize=((AccountInfoDouble(ACCOUNT_BALANCE)/masterAccountBalance)*masterLot)*Bmult;
- }
- else
- if(lotoption == slaveLotCal)
- {
- lotsize = masterLot * (maxDd / recoveryAmount);
- }
- Print("Before Lot Size: ",lotsize);
- if(contractChk)
- {
- int clientContractSize=getDoubleSymbolInfo(symbol,"contract");
- Print("Client Contract size:",clientContractSize);
- if(masterContractSize!=0 && clientContractSize!=0)
- {
- lotsize=((masterContractSize*1.0)/clientContractSize)*lotsize;
- }
- }
- int roundDigit=0;
- double step=getDoubleSymbolInfo(symbol, "lotStep");
- while(step<1)
- {
- roundDigit++;
- step=step*10;
- }
- Print("Round Digits:",roundDigit);
- lotsize = NormalizeDouble(lotsize,roundDigit);
- if(lotsize<getDoubleSymbolInfo(symbol,"minLot"))
- lotsize=getDoubleSymbolInfo(symbol,"minLot");
- else
- if(lotsize>getDoubleSymbolInfo(symbol,"maxLot"))
- lotsize=getDoubleSymbolInfo(symbol,"maxLot");
- Print("Lot Size: ",lotsize);
- return lotsize;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void adminHeartBeat()
- {
- string headers = "apikey:"+localApiKey+"\r\naccept: */* \r\nContent-Type: application/json\r\nUser-Agent: MetaTraderApi";
- string url =localHB_req_link;// Request_link+(string)accountNumber;
- bool isPost;
- int timeout = 100000;
- string lastConnected=TimeToString(TimeCurrent());
- StringReplace(lastConnected,".","-");
- StringReplace(lastConnected," ","T");
- string gmtTime=TimeToString(TimeGMT());
- string jsonData="{\"sLogin\":\""+(string)accountNumber+"\",\"sServer\":\""+clientServer+"\",\"sVersion\":\"5\" ,\"sLastConnected\":\""+gmtTime+"\"}";//\",\"url\":"+"\""+url+"\""+headers+"}";
- uchar data[];
- StringToCharArray(jsonData, data, 0, StringLen(jsonData));
- // Print("Making the heart beat request to the local host");
- POST_function(url,headers,timeout,data,isPost);
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool POST_function(string url, string headers, int timeout, uchar &data[], bool &IsPost)
- {
- ResetLastError(); // clear previous error
- static int lastErrorPrinted = 0;
- uchar result[]; // use uchar for WebRequest result
- string resultHeaders;
- int res = WebRequest("POST", url, headers, timeout, data, result, resultHeaders);
- if(res == 200 || res == 201)
- {
- Print("***Request success. HTTP response code POST: ", res);
- string result_string = CharArrayToString(result);
- Print("content POST: ", result_string);
- lastErrorPrinted = 0; // reset remembered error on success
- IsPost = true;
- return true;
- }
- else
- {
- int err = GetLastError(); // read the error once
- // only print when there's a real error and it's different from last time
- if(err != 0 && err != lastErrorPrinted)
- {
- Print("Get last error: ", err);
- Print("***Request failed. HTTP response code: ", res);
- string result_string = CharArrayToString(result);
- Print("content: ", result_string);
- lastErrorPrinted = err; // remember this error so we don't spam it
- }
- IsPost = false;
- return false;
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void clearOrderArray()
- {
- //Resize to one
- ArrayResize(order_array,1);
- //Clear all data
- order_array[0].symbol = "";
- order_array[0].opentime = 0;
- order_array[0].price = 0;
- order_array[0].ordertype = 0;
- order_array[0].lots = 0;
- order_array[0].stoploss = 0;
- order_array[0].takeprofit = 0;
- order_array[0].ticket = -1;
- order_array[0].magicNo = 0;
- order_array[0].accountBalance=0;
- order_array[0].contractSize=0;
- order_array[0].comments="";
- order_array[0].closedPercentageOfTrade = 0;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void mapHistory()
- {
- for(int i=0; i<PositionsTotal(); i++)
- {
- ulong ticket = PositionGetTicket(i);
- if(PositionSelectByTicket(ticket))
- {
- if(PositionGetInteger(POSITION_MAGIC) > 999)
- {
- addOrderMaster(PositionGetInteger(POSITION_TICKET), PositionGetInteger(POSITION_MAGIC), PositionGetDouble(POSITION_VOLUME), "Market");
- }
- }
- }
- for(int i=0; i<OrdersTotal(); i++)
- {
- ulong ticket = OrderGetTicket(i);
- if(OrderSelect(ticket))
- {
- if(OrderGetInteger(ORDER_MAGIC) > 999)
- {
- addOrderMaster(OrderGetInteger(ORDER_TICKET), OrderGetInteger(ORDER_MAGIC), OrderGetDouble(ORDER_VOLUME_CURRENT), "Pending");
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool addToMarketWatch(string symbol)
- {
- Print("Symbol:",symbol);
- bool result=SymbolSelect(symbol,true);
- if(result)
- {
- Print("Successfully added the symbol or already there:", symbol);
- return true;
- }
- else
- {
- Print("Error in adding symbol:",symbol);
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void read_history_file()
- {
- string file_name = "history_trades.csv";
- if(!FileIsExist(file_name, FILE_COMMON))
- {
- Print("File not found: ", file_name);
- return;
- }
- int h = FileOpen(file_name, FILE_SHARE_READ|FILE_CSV|FILE_COMMON|FILE_READ|FILE_ANSI|FILE_TXT|FILE_COMMON);
- if(h == INVALID_HANDLE)
- {
- Print("Error opening file: ", file_name, " Err:", GetLastError());
- return;
- }
- datetime lastFileModified=(datetime)FileGetInteger(h,FILE_MODIFY_DATE);
- long fileSize=FileGetInteger(h,FILE_SIZE);
- if(lastModified1==lastFileModified && fileSize==lastFileSize1)
- {
- FileClose(h);
- return;
- }
- else
- {
- ulong fileTickets[];
- ArrayResize(fileTickets, 0);
- while(!FileIsEnding(h))
- {
- string line = FileReadString(h);
- // split by comma
- string parts[];
- int count = StringSplit(line,',', parts);
- if(count >= 2)
- {
- // convert to integers
- ulong ticket = StringToInteger(parts[0]);
- ulong magic = StringToInteger(parts[1]);
- int newSize = ArraySize(fileTickets) + 1;
- ArrayResize(fileTickets, newSize);
- fileTickets[newSize - 1] = ticket;
- if(!history_ticket_present(ticket))
- add_history_ticket(ticket, magic);
- }
- else
- {
- // Print("Skipped malformed line while reading ", file_name, " : ", line);
- }
- }
- FileClose(h);
- lastModified1=lastFileModified;
- lastFileSize1=fileSize;
- for(int i = 0; i < MaxOrders; i++)
- {
- ulong tk = historyTradeStore[i].ticket;
- if(tk == -1)
- continue;
- bool found = false;
- for(int j = 0; j < ArraySize(fileTickets); j++)
- {
- if(fileTickets[j] == tk)
- {
- found = true;
- break;
- }
- }
- if(!found)
- {
- Print("Removing ticket not found in file: ", tk, " index=", i);
- historyTradeStore[i].ticket = -1;
- historyTradeStore[i].magic = 0;
- }
- }
- }
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- void add_history_ticket(ulong ticket, ulong magicIs)
- {
- for(int i = 0; i < MaxOrders; i++)
- {
- if(historyTradeStore[i].ticket == -1)
- {
- historyTradeStore[i].ticket = ticket;
- historyTradeStore[i].magic = magicIs;
- Print(" -------- add_history_ticket() Added ticket: ", ticket, " Magic: ", magicIs, " ---------------------------- ");
- return;
- }
- }
- Print("historyTradeStore full, cannot add ticket: ", ticket);
- }
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
- bool history_ticket_present(ulong ticket)
- {
- for(int i = 0 ; i < MaxOrders ; i++)
- {
- if(historyTradeStore[i].ticket == ticket)
- return true;
- }
- return false;
- }
- //+------------------------------------------------------------------+
- //+------------------------------------------------------------------+
- //| |
- //+------------------------------------------------------------------+
|