/*
   Generated by EX4-TO-MQ4 decompiler V4.0.224.1 []
   Website: 
   E-mail :
*/
#property copyright "Forex Robot World Cup"
#property link      "http://www.forex-robot-world-cup.com"

extern string Ver.1.01 = "CobaltFX";
int gi_92 = 30;
int gi_96 = 20;
int gi_100 = 16119285;
int gi_104 = 13882323;
string gs_unused_108 = "CobaltFX V1.13#frwc";
extern double Lots = 0.01;
extern bool UseMM = FALSE;
extern double LotsRiskReductor = 5.0;
extern double MaxLots = 100.0;
int gi_unused_144 = 3;
bool gi_unused_148 = FALSE;
extern string info = "CobaltFX V1.12 - Forex Robot World Cup Edition. No parameters!";
bool gi_160 = FALSE;
bool gi_unused_164 = FALSE;
bool gi_unused_168 = TRUE;
bool gi_172 = FALSE;
bool gi_176 = TRUE;
bool gi_180 = TRUE;
int gi_unused_184 = 12;
int gi_unused_188 = 7;
int gi_192 = 0;
int gi_196 = 0;
string gs_unused_200 = "up";
string gs_unused_208 = "down";
string gs_unused_216 = "none";
string gs_unused_224 = "CobaltFX";
string gs_unused_232 = "mt4instance";
string gs_unused_240 = "fxcm_frwc";
string gs_unused_248 = "rxequity";
int gi_256 = 1;
int g_count_260 = 0;
int g_time_264 = 0;
bool gi_unused_268 = TRUE;
double gd_272 = 0.01;
double gd_unused_280 = 0.01;
double gd_unused_288 = 1.0;
int gi_296 = 2000;
int gi_unused_300 = 2000;
double gd_304 = 1.0;
double gd_unused_312 = 1.0;
int gi_320 = 10;
bool gi_324 = TRUE;
int gi_unused_328 = 70;
int gi_unused_332 = 30;
string gs_336;
int gi_unused_344 = 0;
double g_bid_348 = 0.0;
double gd_unused_356 = 120.0;
int gi_unused_364 = -1;
int gi_unused_368 = 0;
string gs_unused_372 = "EuroOrient Securities&Financial Services Ltd";
string gs_unused_380 = "FXDirectDealer";
string gs_unused_388 = "Interbank FX, LLC";
string gs_unused_396 = "GCI Financial Ltd.";
string gs_unused_404 = "i-Trade FX, LLC";
string gs_unused_412 = "MIG Investments SA";
string gs_unused_420 = "Tadawulfx";
string gs_unused_428 = "Gallant FX";
string gs_unused_436 = "Fienex Group Ltd.";
extern double Slippage = 0.0;
extern int magic = D'08.11.2005 05:32:35';
string gs_cobaltfx_456 = "CobaltFX";
bool gi_464 = FALSE;
int gi_unused_468 = 0;
string gs_472 = "";
bool gi_unused_480 = FALSE;
int gi_484;
double gd_unused_488 = 0.0015;
string g_var_name_496 = "GLOBAL_ORDER_EXECUTED";
string gs_unused_504 = "TRADING_ALLOWED";
string gs_unused_512 = "default";
string gs_520 = "WARN: ";
string gs_528 = "SEVERE: ";
string gs_536 = "INFO: ";
bool gi_unused_544 = FALSE;
double gd_unused_548 = 0.0;
int gi_556;
double g_maxlot_560;
double g_minlot_568;
double g_lotstep_576;
string g_symbol_584;
double gd_592;
int g_slippage_600;
int gi_604;
double gd_608;
int gi_616 = 0;
int gi_620 = 0;
string gs_624;
string gsa_632[] = {".", "..", "...", "....", "....."};
int gi_unused_636 = 0;
int gi_unused_640 = 0;
int gi_644 = 0;
int gi_648 = 0;
int gi_652 = 0;
int gi_656;
int gi_660;
int gi_664;
int gi_668;
int gi_672 = -1;
string gs_676 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int gi_unused_684 = 0;
int gi_unused_688 = 0;
double gda_unused_692[];

string PPrint(int ai_0) {
   int li_4 = MathMod(ai_0, 5);
   return (gsa_632[li_4]);
}

void PrintResponse(int ai_0, int ai_4 = -1, int ai_8 = -1) {
   bool li_12 = FALSE;
   if (gi_672 != ai_0) {
      li_12 = TRUE;
      gi_672 = ai_0;
   }
   if (ai_4 == -1) ai_4 = gi_648;
   if (ai_8 == -1) ai_8 = gi_644;
   gi_648 = ai_4;
   gi_644 = ai_8;
   if (ai_0 & 16384 > 0) PrintLNL(li_12, "Authenticated", gi_100);
   else PrintLNL(li_12, "Authentication failed - error(" + ai_0 + ")", gi_100);
   if (ai_0 & 512 > 0) PrintLNL(li_12, "Attention: Upgrade available", gi_100);
   if (ai_0 & 1024 > 0) PrintLNL(li_12, "Error: Upgrade required", gi_100);
   if (ai_0 & 1 > 0) PrintLNL(li_12, "Error: WinINet initialisation failed", gi_100);
   if (ai_0 & 2 > 0) PrintLNL(li_12, "Error: WinINet connection failed", gi_100);
   if (ai_0 & 4 > 0) PrintLNL(li_12, "Error: Invalid account number", gi_100);
   if (ai_0 & 8 > 0) PrintLNL(li_12, "Error: Invalid account status", gi_100);
   if (ai_0 & 16 > 0) PrintLNL(li_12, "Error: Dll and Expert versions mismatch", gi_100);
   if (ai_0 & 128 > 0) PrintLNL(li_12, "Error: Unable to retrieve authentication code", gi_100);
   if (ai_0 & 256 > 0) PrintLNL(li_12, "Error: Server response failure", gi_100);
   if (ai_0 & 2048 > 0) PrintLNL(li_12, "Error: Invalid authorisation details", gi_100);
   if (ai_0 & 4096 > 0) PrintLNL(li_12, "Error: Authorisation declined", gi_100);
}

string GetObjName(int ai_0) {
   return (StringConcatenate("CobaltFX", " lb: ", ai_0));
}

void GetPos(int ai_0, int &ai_4, int &ai_8) {
   string l_name_12 = GetObjName(ai_0);
   if (ObjectFind(l_name_12) == 0) {
      ai_4 = ObjectGet(l_name_12, OBJPROP_XDISTANCE);
      ai_8 = ObjectGet(l_name_12, OBJPROP_YDISTANCE);
   }
}

void PrintLNL(bool ai_0, string as_4, int ai_12 = -1, int ai_16 = -1, double ad_20 = -1.0, int ai_28 = 0) {
   PrintLN(as_4, ai_12, ai_16, ad_20, ai_28);
   if (ai_0) Print(as_4);
}

void PrintLN(string a_text_0, color a_color_8 = -1, int ai_12 = -1, double ad_16 = -1.0, int ai_24 = 0) {
   if (a_color_8 == CLR_NONE) a_color_8 = gi_100;
   if (ai_12 == -1) ai_12 = gi_648;
   if (ad_16 == -1.0) ad_16 = gi_644;
   string l_name_28 = GetObjName(ai_12);
   if (ObjectFind(l_name_28) != 0) {
      ObjectCreate(l_name_28, OBJ_LABEL, 0, 0, 0);
      ObjectSet(l_name_28, OBJPROP_CORNER, 0);
   }
   ObjectSetText(l_name_28, a_text_0, 8, "Tahoma", a_color_8);
   ObjectSet(l_name_28, OBJPROP_XDISTANCE, gi_660 + ai_24);
   ObjectSet(l_name_28, OBJPROP_YDISTANCE, gi_656 + 14.0 * ad_16);
   if (gi_644 < ad_16 + 1.0) gi_644 = ad_16 + 1.0;
   if (gi_648 < ai_12 + 1) gi_648 = ai_12 + 1;
   if (gi_652 < ai_12) gi_652 = ai_12;
}

void PrintSep(int ai_0 = -1, double ad_4 = -1.0, int ai_12 = 0) {
   if (ai_0 == -1) ai_0 = gi_648;
   if (ad_4 == -1.0) ad_4 = gi_644;
   PrintLN("_______", gi_104, ai_0, ad_4 - 0.3, ai_12);
   if (gi_644 < ad_4 + 1.0) gi_644 = ad_4 + 1.0;
}

void Deleteobjects(int ai_0, int ai_4) {
   for (int li_8 = ai_0; li_8 <= ai_4; li_8++) ObjectDelete(GetObjName(li_8));
}

double Base36Decode(string as_0) {
   int li_24;
   as_0 = StringUpper(as_0);
   int l_str_len_8 = StringLen(as_0);
   double ld_ret_12 = 0;
   for (int li_20 = 0; li_20 < l_str_len_8; li_20++) {
      li_24 = StringFind(gs_676, StringSubstr(as_0, l_str_len_8 - li_20 - 1, 1));
      ld_ret_12 += li_24 * MathPow(36, li_20);
   }
   return (ld_ret_12);
}

string Base36Encode(double ad_0) {
   string l_str_concat_8 = "";
   for (ad_0 = MathAbs(ad_0); ad_0 >= 1.0; ad_0 = MathFloor(ad_0 / 36.0)) l_str_concat_8 = StringConcatenate(StringSubstr(gs_676, MathMod(ad_0, 36), 1), l_str_concat_8);
   return (l_str_concat_8);
}

string StringUpper(string as_0) {
   int li_8;
   int li_20;
   int l_str_len_16 = StringLen(as_0);
   for (int li_12 = 0; li_12 < l_str_len_16; li_12++) {
      li_20 = 0;
      li_8 = StringGetChar(as_0, li_12);
      if (li_8 > '`' && li_8 < '{') li_20 = li_8 - 32;
      if (li_8 > 'ß' && li_8 < 256) li_20 = li_8 - 32;
      if (li_8 == '¸') li_20 = 168;
      if (li_20 > 0) as_0 = StringSetChar(as_0, li_12, li_20);
   }
   return (as_0);
}

string ErrorDescription(int ai_0) {
   string ls_ret_8;
   switch (ai_0) {
   case 0:
   case 1:
      ls_ret_8 = "no error";
      break;
   case 2:
      ls_ret_8 = "common error";
      break;
   case 3:
      ls_ret_8 = "invalid trade parameters";
      break;
   case 4:
      ls_ret_8 = "trade server is busy";
      break;
   case 5:
      ls_ret_8 = "old version of the client terminal";
      break;
   case 6:
      ls_ret_8 = "no connection with trade server";
      break;
   case 7:
      ls_ret_8 = "not enough rights";
      break;
   case 8:
      ls_ret_8 = "too frequent requests";
      break;
   case 9:
      ls_ret_8 = "malfunctional trade operation (never returned error)";
      break;
   case 64:
      ls_ret_8 = "account disabled";
      break;
   case 65:
      ls_ret_8 = "invalid account";
      break;
   case 128:
      ls_ret_8 = "trade timeout";
      break;
   case 129:
      ls_ret_8 = "invalid price";
      break;
   case 130:
      ls_ret_8 = "invalid stops";
      break;
   case 131:
      ls_ret_8 = "invalid trade volume";
      break;
   case 132:
      ls_ret_8 = "market is closed";
      break;
   case 133:
      ls_ret_8 = "trade is disabled";
      break;
   case 134:
      ls_ret_8 = "not enough money";
      break;
   case 135:
      ls_ret_8 = "price changed";
      break;
   case 136:
      ls_ret_8 = "off quotes";
      break;
   case 137:
      ls_ret_8 = "broker is busy (never returned error)";
      break;
   case 138:
      ls_ret_8 = "requote";
      break;
   case 139:
      ls_ret_8 = "order is locked";
      break;
   case 140:
      ls_ret_8 = "long positions only allowed";
      break;
   case 141:
      ls_ret_8 = "too many requests";
      break;
   case 145:
      ls_ret_8 = "modification denied because order too close to market";
      break;
   case 146:
      ls_ret_8 = "trade context is busy";
      break;
   case 147:
      ls_ret_8 = "expirations are denied by broker";
      break;
   case 148:
      ls_ret_8 = "amount of open and pending orders has reached the limit";
      break;
   case 149:
      ls_ret_8 = "hedging is prohibited";
      break;
   case 150:
      ls_ret_8 = "prohibited by FIFO rules";
      break;
   case 4000:
      ls_ret_8 = "no error (never generated code)";
      break;
   case 4001:
      ls_ret_8 = "wrong function pointer";
      break;
   case 4002:
      ls_ret_8 = "array index is out of range";
      break;
   case 4003:
      ls_ret_8 = "no memory for function call stack";
      break;
   case 4004:
      ls_ret_8 = "recursive stack overflow";
      break;
   case 4005:
      ls_ret_8 = "not enough stack for parameter";
      break;
   case 4006:
      ls_ret_8 = "no memory for parameter string";
      break;
   case 4007:
      ls_ret_8 = "no memory for temp string";
      break;
   case 4008:
      ls_ret_8 = "not initialized string";
      break;
   case 4009:
      ls_ret_8 = "not initialized string in array";
      break;
   case 4010:
      ls_ret_8 = "no memory for array\' string";
      break;
   case 4011:
      ls_ret_8 = "too long string";
      break;
   case 4012:
      ls_ret_8 = "remainder from zero divide";
      break;
   case 4013:
      ls_ret_8 = "zero divide";
      break;
   case 4014:
      ls_ret_8 = "unknown command";
      break;
   case 4015:
      ls_ret_8 = "wrong jump (never generated error)";
      break;
   case 4016:
      ls_ret_8 = "not initialized array";
      break;
   case 4017:
      ls_ret_8 = "dll calls are not allowed";
      break;
   case 4018:
      ls_ret_8 = "cannot load library";
      break;
   case 4019:
      ls_ret_8 = "cannot call function";
      break;
   case 4020:
      ls_ret_8 = "expert function calls are not allowed";
      break;
   case 4021:
      ls_ret_8 = "not enough memory for temp string returned from function";
      break;
   case 4022:
      ls_ret_8 = "system is busy (never generated error)";
      break;
   case 4050:
      ls_ret_8 = "invalid function parameters count";
      break;
   case 4051:
      ls_ret_8 = "invalid function parameter value";
      break;
   case 4052:
      ls_ret_8 = "string function internal error";
      break;
   case 4053:
      ls_ret_8 = "some array error";
      break;
   case 4054:
      ls_ret_8 = "incorrect series array using";
      break;
   case 4055:
      ls_ret_8 = "custom indicator error";
      break;
   case 4056:
      ls_ret_8 = "arrays are incompatible";
      break;
   case 4057:
      ls_ret_8 = "global variables processing error";
      break;
   case 4058:
      ls_ret_8 = "global variable not found";
      break;
   case 4059:
      ls_ret_8 = "function is not allowed in testing mode";
      break;
   case 4060:
      ls_ret_8 = "function is not confirmed";
      break;
   case 4061:
      ls_ret_8 = "send mail error";
      break;
   case 4062:
      ls_ret_8 = "string parameter expected";
      break;
   case 4063:
      ls_ret_8 = "integer parameter expected";
      break;
   case 4064:
      ls_ret_8 = "double parameter expected";
      break;
   case 4065:
      ls_ret_8 = "array as parameter expected";
      break;
   case 4066:
      ls_ret_8 = "requested history data in update state";
      break;
   case 4099:
      ls_ret_8 = "end of file";
      break;
   case 4100:
      ls_ret_8 = "some file error";
      break;
   case 4101:
      ls_ret_8 = "wrong file name";
      break;
   case 4102:
      ls_ret_8 = "too many opened files";
      break;
   case 4103:
      ls_ret_8 = "cannot open file";
      break;
   case 4104:
      ls_ret_8 = "incompatible access to a file";
      break;
   case 4105:
      ls_ret_8 = "no order selected";
      break;
   case 4106:
      ls_ret_8 = "unknown symbol";
      break;
   case 4107:
      ls_ret_8 = "invalid price parameter for trade function";
      break;
   case 4108:
      ls_ret_8 = "invalid ticket";
      break;
   case 4109:
      ls_ret_8 = "trade is not allowed in the expert properties";
      break;
   case 4110:
      ls_ret_8 = "longs are not allowed in the expert properties";
      break;
   case 4111:
      ls_ret_8 = "shorts are not allowed in the expert properties";
      break;
   case 4200:
      ls_ret_8 = "object is already exist";
      break;
   case 4201:
      ls_ret_8 = "unknown object property";
      break;
   case 4202:
      ls_ret_8 = "object is not exist";
      break;
   case 4203:
      ls_ret_8 = "unknown object type";
      break;
   case 4204:
      ls_ret_8 = "no object name";
      break;
   case 4205:
      ls_ret_8 = "object coordinates error";
      break;
   case 4206:
      ls_ret_8 = "no specified subwindow";
      break;
   default:
      ls_ret_8 = "unknown error";
   }
   return (ls_ret_8);
}

int init() {
   double l_global_var_4;
   double ld_12;
   gi_660 = gi_96;
   gi_656 = gi_92;
   if (gi_664 != gi_96 || gi_668 != gi_92) {
      gi_664 = gi_96;
      gi_668 = gi_92;
   } else GetPos(0, gi_660, gi_656);
   gi_648 = 0;
   gi_644 = FALSE;
   gs_624 = "CobaltFX" + " ver: " + "1.01";
   PrintLN(gs_624, gi_104);
   PrintSep();
   ObjectsRedraw();
   for (int l_count_0 = 0; !IsStopped() && !IsConnected() || StringLen(AccountName()) <= 0; l_count_0++) {
      PrintLN("Waiting for connection" + PPrint(l_count_0), gi_100, 2, 2);
      ObjectsRedraw();
      Sleep(150);
   }
   PrintLN("Authentication...", gi_100, 2, 2);
   ObjectsRedraw();
   gi_620 = 0;
   gi_616 = 16384;
   PrintResponse(gi_616, 2, 2);
   PrintSep();
   ObjectsRedraw();
   g_symbol_584 = Symbol();
   g_maxlot_560 = MarketInfo(g_symbol_584, MODE_MAXLOT);
   g_minlot_568 = MarketInfo(g_symbol_584, MODE_MINLOT);
   g_lotstep_576 = MarketInfo(g_symbol_584, MODE_LOTSTEP);
   if (g_lotstep_576 == 0.01) gi_556 = 2;
   else {
      if (g_lotstep_576 == 0.1) gi_556 = 1;
      else {
         if (g_lotstep_576 == 1.0) gi_556 = 0;
         else {
            if (g_lotstep_576 == 0.001) gi_556 = 3;
            else gi_556 = 4;
         }
      }
   }
   double l_leverage_20 = AccountLeverage();
   gd_592 = NormalizeDouble(LotsRiskReductor * (100 / l_leverage_20), 2);
   double l_tickvalue_28 = 0.0;
   l_tickvalue_28 = MarketInfo(Symbol(), MODE_TICKVALUE);
   if (gi_464) Print("pipValueUSD: " + l_tickvalue_28);
   if (Digits < 4) {
      gd_608 = 0.001;
      gi_604 = 2;
   } else {
      gd_608 = 0.00001;
      gi_604 = 4;
   }
   g_slippage_600 = Slippage * MathPow(10, Digits - gi_604);
   gi_unused_300 = gi_296;
   if (gi_464) Print("Configuring initial settings...");
   string ls_36 = AccountCompany();
   if (gi_464) Print("AccountCompany: " + ls_36);
   if (gi_464) Print("Account name: " + AccountName());
   if (gi_464) Print("Account number: " + AccountNumber());
   if (gi_464) Print("Account free margin mode: " + AccountFreeMarginMode());
   if (gi_464) Print("Account currency: " + AccountCurrency());
   if (gi_464) Print("Account stopout level: " + AccountStopoutLevel());
   if (gi_464) Print("Account stopout mode: " + AccountStopoutMode());
   if (gi_464) Print("Account leverage: " + AccountLeverage());
   if (gi_464) Print("Account server: " + AccountServer());
   if (gi_464) Print("ServerIP: " + AccountServer());
   if (gi_296 > 9999) {
      gs_336 = "STOP_LOSS > 200 detected, aborting. Please reconfigure...";
      if (gi_464) Print(gs_336);
      gi_unused_480 = FALSE;
      return (1);
   }
   gd_304 = 10;
   gi_unused_480 = TRUE;
   return (0);
}

int deinit() {
   if (gi_464) Print("deinit() invoked. Reason: " + getUnitReasonAsString());
   if (IsTesting()) return (0);
   switch (UninitializeReason()) {
   case REASON_CHARTCLOSE:
   case REASON_REMOVE:
      Deleteobjects(0, gi_652);
      gi_652 = 0;
      break;
   case REASON_RECOMPILE:
   case REASON_CHARTCHANGE:
   case REASON_PARAMETERS:
   case REASON_ACCOUNT:
      Deleteobjects(1, gi_652);
      gi_652 = 1;
   }
   return (0);
}

string getUnitReasonAsString() {
   string ls_ret_0;
   UninitializeReason();
   switch (UninitializeReason()) {
   case REASON_CHARTCLOSE:
      ls_ret_0 = "REASON_CHARTCLOSE";
      break;
   case REASON_REMOVE:
      ls_ret_0 = "REASON_REMOVE";
      break;
   case REASON_RECOMPILE:
      ls_ret_0 = "REASON_RECOMPILE";
      break;
   case REASON_CHARTCHANGE:
      ls_ret_0 = "REASON_CHARTCHANGE";
      break;
   case REASON_PARAMETERS:
      ls_ret_0 = "REASON_PARAMETERS";
      break;
   case REASON_ACCOUNT:
      ls_ret_0 = "REASON_ACCOUNT";
      break;
   default:
      ls_ret_0 = "RHENIUM_UNKNOWN";
   }
   return (ls_ret_0);
}

int getStopLossFor4DigitFormat() {
   return (gi_296);
}

void printPreOrderMarginInfo(double ad_0, double ad_8, double ad_16, double ad_24, double ad_32) {
   if (gi_464) Print("@@pipValueUSD:                     ", ad_0);
   if (gi_464) Print("@@initMarginRequired:              ", ad_8);
   if (gi_464) Print("@@amountUntilStopLoss:             ", ad_16);
   if (gi_464) Print("@@marginBufferForOpenPositions:    ", ad_32);
   if (gi_464) Print("@@=>totalMarginRequiredWorstCase:  ", ad_16 + ad_8 + ad_32);
   if (gi_464) Print("@@=>AccountBalance:                ", AccountBalance());
   if (gi_464) Print("@@AccountFreeMarginCheck:          ", ad_24);
   if (gi_464) Print("@@AccountBalance - initMarginRequired: ", AccountBalance() - ad_8);
}

double get4DigitPipValueUSD(double ad_0) {
   double ld_ret_8 = gd_304 * ad_0;
   if (gi_464) Print("Adjusted PIP Value: " + ld_ret_8);
   return (ld_ret_8);
}

void executeOrder(int a_cmd_0, int ai_unused_4, double ad_8) {
   double ld_20;
   double ld_28;
   double ld_36;
   double ld_44;
   int li_52;
   double ld_56;
   int li_16 = 0;
   if (g_time_264 == Time[0]) {
      if (g_count_260 == gi_256) {
         if (!(gi_464)) return;
         Print(gs_536 + "MAX trades per current bar reached. No trading...");
         return;
      }
   } else {
      g_time_264 = 0;
      g_count_260 = 0;
   }
   if (AccountFreeMargin() >= gi_484) {
      if (gi_324) {
         if (AccountFreeMarginCheck(Symbol(), a_cmd_0, ad_8) <= 0.0 || GetLastError() == 134/* NOT_ENOUGH_MONEY */) {
            gs_472 = getRandomEventId(magic) + "!!! AFMC: Account margin too low! Order will not be executed. Margin: " + AccountFreeMargin();
            if (!(gi_176)) return;
            Print(gs_472);
            return;
         }
         if (gi_464) Print("Performing extended margin checks before order execution...");
         ld_20 = AccountFreeMarginCheck(Symbol(), a_cmd_0, ad_8);
         ld_28 = MarketInfo(Symbol(), MODE_MARGINREQUIRED) * ad_8;
         ld_36 = 0.0;
         ld_44 = 0.0;
         ld_36 = MarketInfo(Symbol(), MODE_TICKVALUE);
         if (gi_464) Print("@@@pipValueOrig: " + ld_36);
         if (ad_8 < 1.0) {
            if (gi_464) Print("@@@volumeLots < 1:", ad_8);
            ld_36 *= ad_8;
         } else
            if (ad_8 > 1.0) ld_36 *= ad_8;
         if (gi_464) Print("@@@pipValue (for lots=" + ad_8 + "): " + ld_36);
         ld_36 = get4DigitPipValueUSD(ld_36);
         ld_44 = ld_36 * getStopLossFor4DigitFormat();
         li_52 = getOpenPositionCount(magic, -1);
         ld_56 = li_52 * ld_44;
         if (ld_28 + ld_44 + ld_56 < AccountFreeMargin() - gi_484) {
            if (gi_464) Print("@@Going to execute order. Account Free Margin(): " + AccountFreeMargin() + ", MIN_FREE_MARGIN: " + gi_484);
            printPreOrderMarginInfo(ld_36, ld_28, ld_44, ld_20, ld_56);
         } else {
            gs_472 = getRandomEventId(magic) + "!!! Account margin too low considering SL. Order will not be executed. Margin: " + AccountFreeMargin();
            if (gi_464) Print(gs_472);
            printPreOrderMarginInfo(ld_36, ld_28, ld_44, ld_20, ld_56);
            return;
         }
         if (a_cmd_0 == OP_SELL) {
            li_16 = sellSingleStopLoss(magic, gs_cobaltfx_456, iHigh(NULL, PERIOD_M1, 0) + gi_296 * gd_608, ad_8);
            if (li_16 == 0) {
               g_bid_348 = Bid;
               g_count_260++;
               g_time_264 = Time[0];
            }
         } else {
            li_16 = buySingleStopLoss(magic, gs_cobaltfx_456, iLow(NULL, PERIOD_M1, 0) - gi_296 * gd_608, ad_8);
            if (li_16 == 0) {
               g_bid_348 = Bid;
               g_count_260++;
               g_time_264 = Time[0];
            }
         }
      } else {
         gs_472 = getRandomEventId(magic) + gs_536 + "Order execution disabled! No order will be opened.";
         if (gi_464) Print(gs_472);
      }
      GlobalVariableSet(g_var_name_496, 1);
   } else {
      gs_472 = getRandomEventId(magic) + "!!! MFMB: Account margin too low. no more orders are executed. Waiting for natural recovery...Margin: " + AccountFreeMargin();
      if (gi_464) Print(gs_472);
   }
}

int closeAllOrdersInPlus(int a_magic_0) {
   bool l_ord_close_4;
   int l_ticket_16;
   int l_cmd_20;
   double l_ask_36;
   double l_bid_44;
   bool li_52;
   double l_ord_lots_56;
   double l_ord_profit_64;
   double l_price_72;
   double l_ord_profit_80;
   int li_unused_88;
   int li_92;
   bool li_8 = FALSE;
   bool li_12 = FALSE;
   bool li_28 = FALSE;
   if (gi_464) Print("--- closeAllOrdersInPlus#Start: Going to CLOSE all + orders of same symbol...");
   for (int l_pos_32 = OrdersTotal() - 1; l_pos_32 >= 0; l_pos_32--) {
      li_28 = FALSE;
      if (OrderSelect(l_pos_32, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == a_magic_0 && Symbol() == OrderSymbol()) {
         RefreshRates();
         l_ask_36 = Ask;
         l_bid_44 = Bid;
         li_52 = FALSE;
         l_ticket_16 = OrderTicket();
         l_cmd_20 = OrderType();
         if (l_cmd_20 == OP_BUY || l_cmd_20 == OP_SELL) {
            if (l_cmd_20 == OP_BUY) {
               if (OrderClosePrice() - OrderOpenPrice() >= gi_320 * gd_608) {
                  if (gi_464) {
                     Print("~~~TEST: OP_BUY: MIN_PROFIT_PIPS reached");
                     Print("~~~TEST: Bid=" + OrderClosePrice());
                     Print("~~~TEST: OrderOpenPrice=" + OrderOpenPrice());
                     Print("~~~TEST: OrderClosePrice=" + OrderClosePrice());
                     Print("~~~TEST: OrderLots=" + OrderLots());
                  }
                  li_52 = TRUE;
               }
            } else {
               if (l_cmd_20 == OP_SELL) {
                  if (OrderOpenPrice() - OrderClosePrice() >= gi_320 * gd_608) {
                     if (gi_464) {
                        Print("~~~TEST: OP_SELL: MIN_PROFIT_PIPS reached");
                        Print("~~~TEST: Ask=" + OrderClosePrice());
                        Print("~~~TEST: OrderOpenPrice=" + OrderOpenPrice());
                        Print("~~~TEST: OrderClosePrice=" + OrderClosePrice());
                        Print("~~~TEST: OrderLots=" + OrderLots());
                     }
                     li_52 = TRUE;
                  }
               }
            }
            if (Ask > l_ask_36 && l_cmd_20 == OP_SELL) {
               logMessage(gs_520 + "ASK price changed to our disadvantage. Position will not be closed..." + "initASK: " + l_ask_36 + ", currentASK: " + Ask);
               li_52 = FALSE;
            } else {
               if (Bid < l_bid_44 && l_cmd_20 == OP_BUY) {
                  logMessage(gs_520 + "BID price changed to our disadvantage. Position will not be closed..." + "initBID: " + l_bid_44 + ", currentBID: " + Bid);
                  li_52 = FALSE;
               } else {
                  l_ord_lots_56 = OrderLots();
                  l_ord_profit_64 = OrderProfit();
                  l_price_72 = OrderClosePrice();
                  l_ord_profit_80 = OrderProfit();
                  li_unused_88 = 0;
                  if (li_52) {
                     li_92 = GetTickCount();
                     if (gi_172) Print("PERF#__before__OrderClose(). Time=" + li_92);
                     while (!IsTradeAllowed()) Sleep(1000);
                     l_ord_close_4 = OrderClose(l_ticket_16, l_ord_lots_56, l_price_72, g_slippage_600, CLR_NONE);
                     if (gi_172) Print("PERF#__after__OrderClose() - closeAllOrdersInPlus(). Elapsed time(ms)=", GetTickCount() - li_92);
                     if (l_ord_close_4) {
                        logMessage("Position successfully closed. ticket=" + l_ticket_16 + ", cid=" + OrderComment() + ", closing price=" + OrderClosePrice() + ", Spread (not active)=" +
                           MarketInfo(OrderSymbol(), MODE_SPREAD));
                        GlobalVariableDel(g_var_name_496);
                        if (li_12) PlaySound("ok.wav");
                        if (gi_464) Print("OrderClose successfully executed");
                        OrderPrint();
                     } else {
                        if (gi_176) Print(gs_528 + "Could not close position. LastError = ", ErrorDescription(GetLastError()), " / ticketId: ", l_ticket_16, " hedgeType(1=true): ", li_28, ", orderClosePrice: ", OrderClosePrice(), ", orderOpenPrice: ", OrderOpenPrice(), ", orderType(0=buy,1=sell): ", OrderType());
                        li_8 = TRUE;
                     }
                     li_52 = FALSE;
                  }
               }
            }
         }
      }
   }
   return (!li_8);
}

int closeAllLossOrders(int a_magic_0) {
   bool l_ord_close_4;
   int l_ticket_16;
   int l_cmd_20;
   double l_ask_36;
   double l_bid_44;
   bool li_52;
   double l_ord_lots_56;
   double l_ord_profit_64;
   double l_price_72;
   double l_ord_profit_80;
   int li_unused_88;
   int li_92;
   bool li_8 = FALSE;
   bool li_12 = FALSE;
   bool li_28 = FALSE;
   if (gi_464) Print("--- closeAllOrdersInPlus#Start: Going to CLOSE all + orders of same symbol...");
   for (int l_pos_32 = OrdersTotal() - 1; l_pos_32 >= 0; l_pos_32--) {
      li_28 = FALSE;
      if (OrderSelect(l_pos_32, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == a_magic_0 && Symbol() == OrderSymbol()) {
         RefreshRates();
         l_ask_36 = Ask;
         l_bid_44 = Bid;
         li_52 = FALSE;
         l_ticket_16 = OrderTicket();
         l_cmd_20 = OrderType();
         if (l_cmd_20 == OP_BUY || l_cmd_20 == OP_SELL) {
            if (l_cmd_20 == OP_BUY) {
               if (OrderOpenPrice() - OrderClosePrice() >= gi_296 * gd_608) {
                  if (gi_464) {
                     Print("~~~TEST: OP_BUY: MIN_PROFIT_PIPS reached");
                     Print("~~~TEST: Bid=" + OrderClosePrice());
                     Print("~~~TEST: OrderOpenPrice=" + OrderOpenPrice());
                     Print("~~~TEST: OrderClosePrice=" + OrderClosePrice());
                     Print("~~~TEST: OrderLots=" + OrderLots());
                  }
                  gi_192++;
                  li_52 = TRUE;
               }
            } else {
               if (l_cmd_20 == OP_SELL) {
                  if (OrderClosePrice() - OrderOpenPrice() >= gi_296 * gd_608) {
                     if (gi_464) {
                        Print("~~~TEST: OP_SELL: MIN_PROFIT_PIPS reached");
                        Print("~~~TEST: Ask=" + OrderClosePrice());
                        Print("~~~TEST: OrderOpenPrice=" + OrderOpenPrice());
                        Print("~~~TEST: OrderClosePrice=" + OrderClosePrice());
                        Print("~~~TEST: OrderLots=" + OrderLots());
                     }
                     gi_196++;
                     li_52 = TRUE;
                  }
               }
            }
            if (Ask > l_ask_36 && l_cmd_20 == OP_SELL) {
               logMessage(gs_520 + "ASK price changed to our disadvantage. Position will not be closed..." + "initASK: " + l_ask_36 + ", currentASK: " + Ask);
               li_52 = FALSE;
            } else {
               if (Bid < l_bid_44 && l_cmd_20 == OP_BUY) {
                  logMessage(gs_520 + "BID price changed to our disadvantage. Position will not be closed..." + "initBID: " + l_bid_44 + ", currentBID: " + Bid);
                  li_52 = FALSE;
               } else {
                  l_ord_lots_56 = OrderLots();
                  l_ord_profit_64 = OrderProfit();
                  l_price_72 = OrderClosePrice();
                  l_ord_profit_80 = OrderProfit();
                  li_unused_88 = 0;
                  if (li_52) {
                     li_92 = GetTickCount();
                     if (gi_172) Print("PERF#__before__OrderClose(). Time=" + li_92);
                     while (!IsTradeAllowed()) Sleep(1000);
                     l_ord_close_4 = OrderClose(l_ticket_16, l_ord_lots_56, l_price_72, g_slippage_600, CLR_NONE);
                     if (gi_172) Print("PERF#__after__OrderClose() - closeAllOrdersInPlus(). Elapsed time(ms)=", GetTickCount() - li_92);
                     if (l_ord_close_4) {
                        logMessage("Position successfully closed. ticket=" + l_ticket_16 + ", cid=" + OrderComment() + ", closing price=" + OrderClosePrice() + ", Spread (not active)=" +
                           MarketInfo(OrderSymbol(), MODE_SPREAD));
                        GlobalVariableDel(g_var_name_496);
                        if (li_12) PlaySound("ok.wav");
                        if (gi_464) Print("OrderClose successfully executed");
                        OrderPrint();
                     } else {
                        if (gi_176) Print(gs_528 + "Could not close position. LastError = ", ErrorDescription(GetLastError()), " / ticketId: ", l_ticket_16, " hedgeType(1=true): ", li_28, ", orderClosePrice: ", OrderClosePrice(), ", orderOpenPrice: ", OrderOpenPrice(), ", orderType(0=buy,1=sell): ", OrderType());
                        li_8 = TRUE;
                     }
                     li_52 = FALSE;
                  }
               }
            }
         }
      }
   }
   return (!li_8);
}

int isSettingSLAllowedBroker() {
   return (0);
}

string getRandomEventId(int ai_0) {
   MathSrand(TimeLocal());
   string ls_ret_4 = GetTickCount();
   ls_ret_4 = ai_0 + "_" + ls_ret_4 + "_" + MathRand() + ": ";
   return (ls_ret_4);
}

int buySingleStopLoss(int a_magic_0, string a_comment_4, double a_price_12, double a_lots_20) {
   int l_error_28;
   string l_symbol_32 = Symbol();
   int li_unused_40 = 5;
   RefreshRates();
   double l_ask_44 = MarketInfo(l_symbol_32, MODE_ASK);
   double l_bid_52 = MarketInfo(l_symbol_32, MODE_BID);
   double l_point_60 = MarketInfo(l_symbol_32, MODE_POINT);
   int li_unused_68 = MarketInfo(l_symbol_32, MODE_DIGITS);
   int li_unused_72 = MarketInfo(l_symbol_32, MODE_SPREAD);
   if (gi_464) Print(l_symbol_32 + " - askPrice: " + l_ask_44);
   if (gi_464) Print(l_symbol_32 + " - bidPrice: " + l_bid_52);
   if (gi_464) Print(l_symbol_32 + " - point: " + l_point_60);
   if (gi_464) Print(Symbol() + " / Going to buy. SL=" + a_price_12 + ", Ask=", Ask, ", Lots=", a_lots_20, ", cid=", a_comment_4);
   if (isSettingSLAllowedBroker() == 0) a_price_12 = 0;
   int li_80 = GetTickCount();
   if (gi_172) Print("PERF#__before__OrderSend(). Time=" + li_80);
   while (!IsTradeAllowed()) Sleep(1000);
   int l_ticket_76 = OrderSend(l_symbol_32, OP_BUY, a_lots_20, Ask, g_slippage_600, a_price_12, 0, a_comment_4, a_magic_0, 0, Green);
   if (gi_172) Print("PERF#__after__OrderSend() - buySingleStopLoss(). Elapsed time(ms)=", GetTickCount() - li_80);
   if (l_ticket_76 < 1) {
      if (gi_176) Print("Buy error");
      l_error_28 = GetLastError();
      if (gi_176) Print("Error = ", ErrorDescription(l_error_28));
      if (gi_160) PlaySound("timeout.wav");
      return (99942);
   }
   if (gi_160) PlaySound("expert.wav");
   OrderPrint();
   return (0);
}

int sellSingleStopLoss(int a_magic_0, string a_comment_4, double a_price_12, double a_lots_20) {
   int l_error_28;
   string l_symbol_32 = Symbol();
   int li_unused_40 = 5;
   RefreshRates();
   double l_ask_44 = MarketInfo(l_symbol_32, MODE_ASK);
   double l_bid_52 = MarketInfo(l_symbol_32, MODE_BID);
   double l_point_60 = MarketInfo(l_symbol_32, MODE_POINT);
   int li_unused_68 = MarketInfo(l_symbol_32, MODE_DIGITS);
   int li_unused_72 = MarketInfo(l_symbol_32, MODE_SPREAD);
   if (gi_464) Print(l_symbol_32 + " - askPrice: " + l_ask_44);
   if (gi_464) Print(l_symbol_32 + " - bidPrice: " + l_bid_52);
   if (gi_464) Print(l_symbol_32 + " - point: " + l_point_60);
   if (gi_464) Print(Symbol() + " / Going to sell. SL=" + a_price_12 + ", Bid=", Bid, ", Lots=", a_lots_20, ", cid=", a_comment_4);
   if (isSettingSLAllowedBroker() == 0) a_price_12 = 0;
   l_bid_52 = MarketInfo(l_symbol_32, MODE_BID);
   int li_80 = GetTickCount();
   if (gi_172) Print("PERF#__before__OrderSend(). Time=" + li_80);
   while (!IsTradeAllowed()) Sleep(1000);
   int l_ticket_76 = OrderSend(l_symbol_32, OP_SELL, a_lots_20, Bid, g_slippage_600, a_price_12, 0, a_comment_4, a_magic_0, 0, Red);
   if (gi_172) Print("PERF#__after__OrderSend() - sellSingleStopLoss(). Elapsed time(ms)=", GetTickCount() - li_80);
   if (l_ticket_76 < 1) {
      if (gi_176) Print("Sell error");
      l_error_28 = GetLastError();
      if (gi_176) Print("Error = ", ErrorDescription(l_error_28));
      if (gi_160) PlaySound("timeout.wav");
      return (99942);
   }
   if (gi_160) PlaySound("expert.wav");
   OrderPrint();
   return (0);
}

int getOpenPositionCount(int a_magic_0, int ai_4) {
   int l_count_12 = 0;
   int l_count_16 = 0;
   for (int l_pos_8 = OrdersTotal() - 1; l_pos_8 >= 0; l_pos_8--) {
      if (OrderSelect(l_pos_8, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderMagicNumber() != a_magic_0 && a_magic_0 != 0) continue;
         if (OrderType() != OP_BUY && OrderType() != OP_SELL) continue;
         if (OrderType() == OP_BUY) l_count_12++;
         else
            if (OrderType() == OP_SELL) l_count_16++;
      }
   }
   if (gi_464) Print("Open positions: ", l_count_12 + l_count_16);
   if (ai_4 == -1) return (l_count_12 + l_count_16);
   if (ai_4 == 0) return (l_count_12);
   if (ai_4 == 1) return (l_count_16);
   return (0);
}

void logMessage(string as_0) {
   if (!gi_180) Print(as_0);
}

int start() {
   if (!IsTesting() || IsVisualMode()) {
      GetPos(0, gi_660, gi_656);
      gi_648 = 0;
      gi_644 = FALSE;
      PrintLN(gs_624, gi_104);
      PrintSep();
      PrintResponse(gi_616 | gi_620);
      PrintSep();
      Deleteobjects(gi_648, gi_652);
      gi_652 = gi_648 - 1;
      ObjectsRedraw();
   }
   gi_320 = 150;
   gd_unused_288 = 1;
   gd_272 = LotsOptimized();
   gd_unused_280 = 0.01;
   if (NumberOrders(-1, magic) > 9) {
      closeAllOrdersInPlus(magic);
      closeAllLossOrders(magic);
      return (0);
   }
   if (g_bid_348 == 0.0) g_bid_348 = Bid;
   else {
      if (open_sell(Bid, g_bid_348)) {
         executeOrder(OP_SELL, 0, gd_272);
         gi_unused_364 = 1;
      } else {
         if (open_buy(Bid, g_bid_348)) {
            executeOrder(OP_BUY, 0, gd_272);
            gi_unused_364 = 0;
         }
      }
   }
   gi_296 = 1300;
   closeAllOrdersInPlus(magic);
   closeAllLossOrders(magic);
   return (0);
}

double LotsOptimized() {
   double ld_ret_0;
   double ld_8;
   double ld_16;
   if (!UseMM) ld_ret_0 = Lots;
   else {
      ld_8 = AccountFreeMargin() * gd_592 / 100.0;
      ld_16 = MarketInfo(g_symbol_584, MODE_MARGINREQUIRED) * g_lotstep_576;
      ld_ret_0 = NormalizeDouble(MathFloor(ld_8 / ld_16) * g_lotstep_576, gi_556);
   }
   if (ld_ret_0 > MaxLots) ld_ret_0 = MaxLots;
   if (ld_ret_0 < g_minlot_568) ld_ret_0 = g_minlot_568;
   else
      if (ld_ret_0 > g_maxlot_560) ld_ret_0 = g_maxlot_560;
   return (ld_ret_0);
}

int NumberOrders(int ai_0, int a_magic_4) {
   int l_count_8 = 0;
   int li_12 = OrdersTotal() - 1;
   for (int l_pos_16 = li_12; l_pos_16 >= 0; l_pos_16--) {
      if (!OrderSelect(l_pos_16, SELECT_BY_POS, MODE_TRADES)) Print("NumberOrders: OrderSelect() error = ", ErrorDescription(GetLastError()));
      else {
         if (OrderMagicNumber() == a_magic_4) {
            if (ai_0 >= 0)
               if (OrderType() % 2 != ai_0) continue;
            if (OrderSymbol() == g_symbol_584) l_count_8++;
         }
      }
   }
   return (l_count_8);
}

bool open_buy(double a1, double a2) {
   return (a2 - a1 > 0.0015);
}

bool open_sell(double a1, double a2) {
   return (a1 - a2 > 0.0015);
}