Jkinstrading

Robot files

Two ways to run it: connected, or completely on its own

The bridge turns any MetaTrader account into an arm of Jkinstrading — the engine here decides, the terminal executes. The standalone robot carries the whole strategy inside the terminal for when a VPS has no internet access to this app.

Jkinstrading_Bridge.mq5

Connected mode. Streams prices to Jkinstrading every few seconds, executes OPEN and CLOSE commands, and manages the money stop, the three targets, the partial closes, the break-even lock and the trailing on the account itself. 763 lines.

Download bridge

MA50_Cross_EA.mq5

Standalone mode. The same strategy and the same money management, decided inside MetaTrader with no connection to this app. 763 lines.

Download standalone

Connect a platform in five steps

  1. 1 Add your account on the Platforms page (MT5, MT4, cTrader or REST) and copy the connection key it generates.
  2. 2 In MetaTrader: File > Open Data Folder > MQL5 > Experts, save Jkinstrading_Bridge.mq5 there and press F7 in MetaEditor — 0 errors, 0 warnings.
  3. 3 Tools > Options > Expert Advisors: tick Allow WebRequest for listed URL and add this app's address exactly as it appears in your browser.
  4. 4 Drag the bridge onto a chart of the symbol you want traded, paste the app URL and the connection key, allow algorithmic trading.
  5. 5 Back here, set the strategy numbers, press Start robot, and watch the signal log — the engine evaluates every sync and the bridge executes.
Allow this app's address under Tools > Options > Expert Advisors > Allow WebRequest for listed URL. Without it MetaTrader blocks every sync with error 4014.

Standalone install and test

  1. 1 Save MA50_Cross_EA.mq5 into MQL5/Experts (File > Open Data Folder in MetaTrader 5), then press F7 in MetaEditor: the log must read 0 errors, 0 warnings.
  2. 2 In the terminal refresh the Navigator, drag the EA onto an M15 or H1 chart and allow algorithmic trading in the dialog and in the toolbar.
  3. 3 Open the Strategy Tester (Ctrl+R): pick the symbol, M15, Every tick based on real ticks, a 3-6 month date range and your real account's leverage and deposit currency.
  4. 4 Start with lots 0.10, SL 20, TP1 10, TP2 20, TP3 40, partials 50% and 25%, break-even 8/2, trailing 15/8/2, then read the Journal tab for any retcode message.
  5. 5 Forward-test on a demo account for at least two weeks before live use, and re-tune the money values whenever you change the lot size, the symbol or the account currency.

Bridge source · 763 lines

Jkinstrading_Bridge.mq5

Download file
//+------------------------------------------------------------------+
//|                                          Jkinstrading_Bridge.mq5 |
//|  Universal bridge between Jkinstrading and any MetaTrader 5      |
//|  broker account (Exness, Deriv, XM, IC Markets, FBS, Pepperstone |
//|  and every other MT5 server).                                     |
//|                                                                   |
//|  The robot brain runs in the Jkinstrading app. This EA streams    |
//|  prices to it, receives commands, executes them and manages the   |
//|  money based stops, targets, partial closes and trailing locally. |
//|  Works on hedging and netting accounts.                          |
//+------------------------------------------------------------------+
#property copyright "Jkinstrading"
#property version   "1.10"
#property description "Jkinstrading bridge: streams prices to the app, executes its commands, manages money stops locally."

#include <Trade\Trade.mqh>

input group "=== Jkinstrading connection ==="
input string InpServerUrl   = "https://your-app-url";  // App URL, no trailing slash
input string InpApiKey      = "jkt_xxxxxxxxxxxxxxxx";  // Connection key from the Platforms page
input int    InpSyncSeconds = 5;                       // Seconds between syncs
input int    InpBarsToSend  = 200;                     // Closes sent per sync
input string InpTradeSymbol = "";                      // Symbol ("" = chart symbol)

input group "=== Execution ==="
input long   InpMagic       = 505050;                  // Magic number
input int    InpSlippage    = 30;                      // Deviation in points
input string InpComment     = "Jkinstrading";          // Order comment
input bool   InpAllowTrade  = true;                    // Master switch on this terminal

input group "=== Local fallbacks (used until the first sync answers) ==="
input double InpFbLots      = 0.10;                    // Lot size
input double InpFbSL        = 20.0;                    // Stop loss in money
input double InpFbTP1       = 10.0;                    // Target 1 in money
input double InpFbTP2       = 20.0;                    // Target 2 in money
input double InpFbTP3       = 40.0;                    // Target 3 in money

//--- state received from the app
CTrade   trade;
string   g_symbol        = "";
string   g_url           = "";
bool     g_running       = false;
bool     g_synced        = false;
double   g_lots          = 0.10;
double   g_sl            = 20.0;
double   g_tp1           = 10.0;
double   g_tp2           = 20.0;
double   g_tp3           = 40.0;
bool     g_usePartial    = true;
double   g_partial1      = 50.0;
double   g_partial2      = 25.0;
double   g_lockAfterTP1  = 2.0;
bool     g_useBE         = true;
double   g_beTrigger     = 8.0;
double   g_beLock        = 2.0;
bool     g_useTrail      = true;
double   g_trailStart    = 15.0;
double   g_trailDist     = 8.0;
double   g_trailStep     = 2.0;

//--- symbol cache
int      g_digits        = 0;
double   g_point         = 0.0;
double   g_volStep       = 0.0;
double   g_volMin        = 0.0;
double   g_volMax        = 0.0;
int      g_volDigits     = 2;

//--- command acknowledgements waiting to be reported
string   g_done          = "";

//+------------------------------------------------------------------+
//| Init                                                             |
//+------------------------------------------------------------------+
int OnInit()
  {
   g_symbol = (StringLen(InpTradeSymbol)>0 ? InpTradeSymbol : _Symbol);
   if(!SymbolSelect(g_symbol,true))
     {
      Print("Init error: symbol ",g_symbol," is not available on this account.");
      return(INIT_PARAMETERS_INCORRECT);
     }

   g_url = InpServerUrl;
   while(StringLen(g_url)>0 && StringSubstr(g_url,StringLen(g_url)-1,1)=="/")
      g_url = StringSubstr(g_url,0,StringLen(g_url)-1);
   if(StringLen(g_url)<8 || StringFind(g_url,"http")!=0)
     {
      Print("Init error: set InpServerUrl to the Jkinstrading app address.");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(StringLen(InpApiKey)<8)
     {
      Print("Init error: paste the connection key from the Platforms page.");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpSyncSeconds<1)
     {
      Print("Init error: sync interval must be 1 second or more.");
      return(INIT_PARAMETERS_INCORRECT);
     }

   g_digits  = (int)SymbolInfoInteger(g_symbol,SYMBOL_DIGITS);
   g_point   = SymbolInfoDouble(g_symbol,SYMBOL_POINT);
   g_volStep = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_STEP);
   g_volMin  = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MIN);
   g_volMax  = SymbolInfoDouble(g_symbol,SYMBOL_VOLUME_MAX);
   if(g_point<=0.0)
      g_point = 1.0/MathPow(10.0,(double)g_digits);
   if(g_volStep<=0.0)
      g_volStep = 0.01;
   if(g_volMin<=0.0)
      g_volMin = g_volStep;
   if(g_volMax<=0.0)
      g_volMax = 100.0;

   g_volDigits = 0;
   double step = g_volStep;
   while(step<1.0 && g_volDigits<8)
     {
      step *= 10.0;
      g_volDigits++;
     }

   g_lots = InpFbLots;
   g_sl   = InpFbSL;
   g_tp1  = InpFbTP1;
   g_tp2  = InpFbTP2;
   g_tp3  = InpFbTP3;

   trade.SetExpertMagicNumber((ulong)InpMagic);
   trade.SetDeviationInPoints((ulong)MathMax(0,InpSlippage));
   trade.SetTypeFillingBySymbol(g_symbol);
   trade.SetMarginMode();
   trade.LogLevel(LOG_LEVEL_ERRORS);

   EventSetTimer(InpSyncSeconds);
   Print("Jkinstrading bridge online. Symbol ",g_symbol," url ",g_url);
   Sync();
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
   Print("Jkinstrading bridge stopped. Reason code ",(string)reason);
  }

//+------------------------------------------------------------------+
//| Helpers                                                          |
//+------------------------------------------------------------------+
string TimeframeName()
  {
   string name = EnumToString((ENUM_TIMEFRAMES)_Period);
   int cut = StringFind(name,"_");
   if(cut>=0)
      name = StringSubstr(name,cut+1);
   return(name);
  }

string UrlEncode(const string text)
  {
   string out = "";
   int len = StringLen(text);
   for(int i=0; i<len; i++)
     {
      string ch = StringSubstr(text,i,1);
      ushort code = StringGetCharacter(text,i);
      bool safe = ((code>=48 && code<=57) || (code>=65 && code<=90) || (code>=97 && code<=122) ||
                   ch=="-" || ch=="_" || ch=="." || ch=="~");
      if(safe)
         out += ch;
      else
         if(ch==" ")
            out += "+";
         else
            out += "%"+StringFormat("%02X",(int)code);
     }
   return(out);
  }

double MoneyToPrice(const double money,const double volume)
  {
   if(money<=0.0 || volume<=0.0)
      return(0.0);
   double tickValue = SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_VALUE);
   double tickSize  = SymbolInfoDouble(g_symbol,SYMBOL_TRADE_TICK_SIZE);
   if(tickValue<=0.0 || tickSize<=0.0)
      return(0.0);
   double perPrice = (tickValue/tickSize)*volume;
   if(perPrice<=0.0)
      return(0.0);
   return(money/perPrice);
  }

double NormalizeLots(const double volume)
  {
   if(g_volStep<=0.0)
      return(0.0);
   double v = MathFloor(volume/g_volStep+0.5)*g_volStep;
   v = NormalizeDouble(v,g_volDigits);
   if(v<g_volMin)
      v = g_volMin;
   if(v>g_volMax)
      v = g_volMax;
   return(NormalizeDouble(v,g_volDigits));
  }

double FloorLots(const double volume)
  {
   if(g_volStep<=0.0 || volume<=0.0)
      return(0.0);
   double v = MathFloor(volume/g_volStep+0.0000001)*g_volStep;
   return(NormalizeDouble(v,g_volDigits));
  }

double StopsDistance()
  {
   long level = (long)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_STOPS_LEVEL);
   if(level<0)
      level = 0;
   return((double)level*g_point);
  }

bool FreezeBlocks(const bool isBuy,const double currentSL,const double currentTP)
  {
   long level = (long)SymbolInfoInteger(g_symbol,SYMBOL_TRADE_FREEZE_LEVEL);
   if(level<=0)
      return(false);
   double freeze = (double)level*g_point;
   double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID);
   double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK);
   if(isBuy)
     {
      if(currentSL>0.0 && (bid-currentSL)<freeze)
         return(true);
      if(currentTP>0.0 && (currentTP-bid)<freeze)
         return(true);
      return(false);
     }
   if(currentSL>0.0 && (currentSL-ask)<freeze)
      return(true);
   if(currentTP>0.0 && (ask-currentTP)<freeze)
      return(true);
   return(false);
  }

void AdjustStops(const bool isBuy,double &sl,double &tp)
  {
   double minDist = StopsDistance();
   double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID);
   double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK);
   if(isBuy)
     {
      if(sl>0.0 && sl>(bid-minDist))
         sl = bid-minDist;
      if(tp>0.0 && tp<(ask+minDist))
         tp = ask+minDist;
     }
   else
     {
      if(sl>0.0 && sl<(ask+minDist))
         sl = ask+minDist;
      if(tp>0.0 && tp>(bid-minDist))
         tp = bid-minDist;
     }
   if(sl<0.0)
      sl = 0.0;
   if(tp<0.0)
      tp = 0.0;
   if(sl>0.0)
      sl = NormalizeDouble(sl,g_digits);
   if(tp>0.0)
      tp = NormalizeDouble(tp,g_digits);
  }

string GVName(const ulong ticket,const string suffix)
  {
   return("JKT_"+IntegerToString(InpMagic)+"_"+IntegerToString((long)ticket)+"_"+suffix);
  }

int PositionStage(const ulong ticket)
  {
   string name = GVName(ticket,"stage");
   if(!GlobalVariableCheck(name))
      return(0);
   return((int)GlobalVariableGet(name));
  }

void SetPositionStage(const ulong ticket,const int stage)
  {
   GlobalVariableSet(GVName(ticket,"stage"),(double)stage);
  }

double OriginalVolume(const ulong ticket,const double currentVolume)
  {
   string name = GVName(ticket,"vol");
   if(!GlobalVariableCheck(name))
     {
      GlobalVariableSet(name,currentVolume);
      return(currentVolume);
     }
   double stored = GlobalVariableGet(name);
   if(stored<=0.0)
     {
      GlobalVariableSet(name,currentVolume);
      return(currentVolume);
     }
   return(stored);
  }

void CleanupGlobals()
  {
   string prefix = "JKT_"+IntegerToString(InpMagic)+"_";
   for(int i=GlobalVariablesTotal()-1; i>=0; i--)
     {
      string name = GlobalVariableName(i);
      if(StringFind(name,prefix)!=0)
         continue;
      string rest = StringSubstr(name,StringLen(prefix));
      int sep = StringFind(rest,"_");
      if(sep<=0)
         continue;
      ulong ticket = (ulong)StringToInteger(StringSubstr(rest,0,sep));
      if(ticket==0 || !PositionSelectByTicket(ticket))
         GlobalVariableDel(name);
     }
  }

//+------------------------------------------------------------------+
//| Position management (money stops, partials, trailing)            |
//+------------------------------------------------------------------+
bool MoveStopLoss(const ulong ticket,const bool isBuy,double newSL,double &currentSL,const double currentTP)
  {
   if(newSL<=0.0)
      return(false);
   newSL = NormalizeDouble(newSL,g_digits);
   double tolerance = g_point*0.5;
   if(isBuy && currentSL>0.0 && newSL<=(currentSL+tolerance))
      return(false);
   if(!isBuy && currentSL>0.0 && newSL>=(currentSL-tolerance))
      return(false);

   double minDist = StopsDistance();
   double bid = SymbolInfoDouble(g_symbol,SYMBOL_BID);
   double ask = SymbolInfoDouble(g_symbol,SYMBOL_ASK);
   if(isBuy && newSL>(bid-minDist))
      return(false);
   if(!isBuy && newSL<(ask+minDist))
      return(false);
   if(FreezeBlocks(isBuy,currentSL,currentTP))
      return(false);

   double tp = (currentTP>0.0 ? NormalizeDouble(currentTP,g_digits) : 0.0);
   if(!trade.PositionModify(ticket,newSL,tp))
     {
      Print("Modify SL failed, ticket ",(string)ticket," retcode=",(string)trade.ResultRetcode()," ",
            trade.ResultRetcodeDescription());
      return(false);
     }
   currentSL = newSL;
   return(true);
  }

void ClosePartial(const ulong ticket,const double originalVolume,const double currentVolume,const double percent)
  {
   if(percent<=0.0 || currentVolume<=0.0)
      return;
   double want = FloorLots(originalVolume*percent/100.0);
   if(want<=0.0)
      return;
   if(want>(currentVolume-g_volStep*0.5))
      want = FloorLots(currentVolume-g_volStep);
   if(want<g_volMin-0.0000001)
      return;
   if((currentVolume-want)<(g_volMin-0.0000001))
      return;
   if(!trade.PositionClosePartial(ticket,want))
      Print("Partial close failed, ticket ",(string)ticket," retcode=",(string)trade.ResultRetcode()," ",
            trade.ResultRetcodeDescription());
  }

double TargetPrice(const double entry,const bool isBuy,const double money,const double volume)
  {
   double dist = MoneyToPrice(money,volume);
   if(dist<=0.0)
      return(0.0);
   return(NormalizeDouble(isBuy ? entry+dist : entry-dist,g_digits));
  }

bool TargetReached(const bool isBuy,const double marketPrice,const double target)
  {
   if(target<=0.0)
      return(false);
   if(isBuy)
      return(marketPrice>=target);
   return(marketPrice<=target);
  }

void ManagePositions()
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;

      bool   isBuy  = (PositionGetInteger(POSITION_TYPE)==(long)POSITION_TYPE_BUY);
      double curVol = PositionGetDouble(POSITION_VOLUME);
      double entry  = PositionGetDouble(POSITION_PRICE_OPEN);
      double curSL  = PositionGetDouble(POSITION_SL);
      double curTP  = PositionGetDouble(POSITION_TP);
      double profit = PositionGetDouble(POSITION_PROFIT);
      double bid    = SymbolInfoDouble(g_symbol,SYMBOL_BID);
      double ask    = SymbolInfoDouble(g_symbol,SYMBOL_ASK);
      double market = (isBuy ? bid : ask);
      if(curVol<=0.0 || entry<=0.0 || market<=0.0)
         continue;

      double origVol  = OriginalVolume(ticket,curVol);
      int    stage    = PositionStage(ticket);
      double tp1Price = TargetPrice(entry,isBuy,g_tp1,origVol);
      double tp2Price = TargetPrice(entry,isBuy,g_tp2,origVol);

      if(stage<1 && TargetReached(isBuy,market,tp1Price))
        {
         if(g_usePartial)
            ClosePartial(ticket,origVol,curVol,g_partial1);
         SetPositionStage(ticket,1);
         double lockDist = MoneyToPrice(g_lockAfterTP1,origVol);
         if(lockDist>0.0)
            MoveStopLoss(ticket,isBuy,(isBuy ? entry+lockDist : entry-lockDist),curSL,curTP);
         continue;
        }

      if(stage==1 && TargetReached(isBuy,market,tp2Price))
        {
         if(g_usePartial)
            ClosePartial(ticket,origVol,curVol,g_partial2);
         SetPositionStage(ticket,2);
         MoveStopLoss(ticket,isBuy,(tp1Price>0.0 ? tp1Price : entry),curSL,curTP);
         continue;
        }

      if(g_useBE && g_beTrigger>0.0 && profit>=g_beTrigger)
        {
         double lockDist = MoneyToPrice(g_beLock,curVol);
         double target   = (g_beLock<=0.0 ? entry : (isBuy ? entry+lockDist : entry-lockDist));
         MoveStopLoss(ticket,isBuy,target,curSL,curTP);
        }

      if(g_useTrail && g_trailDist>0.0 && profit>=g_trailStart)
        {
         double trailDist = MoneyToPrice(g_trailDist,curVol);
         double stepDist  = MoneyToPrice(g_trailStep,curVol);
         if(trailDist>0.0)
           {
            double candidate = (isBuy ? market-trailDist : market+trailDist);
            bool   improves  = true;
            if(curSL>0.0 && stepDist>0.0)
               improves = (isBuy ? (candidate-curSL)>=stepDist : (curSL-candidate)>=stepDist);
            if(improves)
               MoveStopLoss(ticket,isBuy,candidate,curSL,curTP);
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Counting and closing                                             |
//+------------------------------------------------------------------+
int CountPositions(const int direction)
  {
   int count = 0;
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0 || !PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      long type = PositionGetInteger(POSITION_TYPE);
      if(direction>0 && type!=(long)POSITION_TYPE_BUY)
         continue;
      if(direction<0 && type!=(long)POSITION_TYPE_SELL)
         continue;
      count++;
     }
   return(count);
  }

double FloatingProfit()
  {
   double sum = 0.0;
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0 || !PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      sum += PositionGetDouble(POSITION_PROFIT);
     }
   return(sum);
  }

int ClosePositions(const int direction)
  {
   int closed = 0;
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0 || !PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=g_symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      bool isBuy = (PositionGetInteger(POSITION_TYPE)==(long)POSITION_TYPE_BUY);
      if(direction>0 && !isBuy)
         continue;
      if(direction<0 && isBuy)
         continue;
      if(FreezeBlocks(isBuy,PositionGetDouble(POSITION_SL),PositionGetDouble(POSITION_TP)))
         continue;
      if(trade.PositionClose(ticket))
        {
         GlobalVariableDel(GVName(ticket,"stage"));
         GlobalVariableDel(GVName(ticket,"vol"));
         closed++;
        }
      else
         Print("Close failed, ticket ",(string)ticket," retcode=",(string)trade.ResultRetcode()," ",
               trade.ResultRetcodeDescription());
     }
   return(closed);
  }

bool OpenTrade(const bool isBuy,const double requestedLots)
  {
   double lots = NormalizeLots(requestedLots>0.0 ? requestedLots : g_lots);
   if(lots<=0.0)
      return(false);
   double price = (isBuy ? SymbolInfoDouble(g_symbol,SYMBOL_ASK) : SymbolInfoDouble(g_symbol,SYMBOL_BID));
   if(price<=0.0)
      return(false);

   double slDist = MoneyToPrice(g_sl,lots);
   double tpDist = MoneyToPrice(g_tp3,lots);
   double sl = 0.0;
   double tp = 0.0;
   if(slDist>0.0)
      sl = (isBuy ? price-slDist : price+slDist);
   if(tpDist>0.0)
      tp = (isBuy ? price+tpDist : price-tpDist);
   AdjustStops(isBuy,sl,tp);

   bool ok = (isBuy ? trade.Buy(lots,g_symbol,0.0,sl,tp,InpComment)
              : trade.Sell(lots,g_symbol,0.0,sl,tp,InpComment));
   if(!ok)
     {
      Print("Open ",(isBuy ? "BUY" : "SELL")," failed, retcode=",(string)trade.ResultRetcode()," ",
            trade.ResultRetcodeDescription());
      return(false);
     }
   Print("Opened ",(isBuy ? "BUY" : "SELL")," ",DoubleToString(lots,g_volDigits)," ",g_symbol,
         " at ",DoubleToString(trade.ResultPrice(),g_digits));
   return(true);
  }

//+------------------------------------------------------------------+
//| Protocol                                                         |
//+------------------------------------------------------------------+
void Acknowledge(const string id,const string result)
  {
   if(StringLen(g_done)>0)
      g_done += ",";
   g_done += id+":"+result;
  }

void ApplyStatus(string &parts[])
  {
   int n = ArraySize(parts);
   if(n<18)
      return;
   g_running      = (StringToInteger(parts[1])==1);
   g_lots         = StringToDouble(parts[2]);
   g_sl           = StringToDouble(parts[3]);
   g_tp1          = StringToDouble(parts[4]);
   g_tp2          = StringToDouble(parts[5]);
   g_tp3          = StringToDouble(parts[6]);
   g_usePartial   = (StringToInteger(parts[7])==1);
   g_partial1     = StringToDouble(parts[8]);
   g_partial2     = StringToDouble(parts[9]);
   g_lockAfterTP1 = StringToDouble(parts[10]);
   g_useBE        = (StringToInteger(parts[11])==1);
   g_beTrigger    = StringToDouble(parts[12]);
   g_beLock       = StringToDouble(parts[13]);
   g_useTrail     = (StringToInteger(parts[14])==1);
   g_trailStart   = StringToDouble(parts[15]);
   g_trailDist    = StringToDouble(parts[16]);
   g_trailStep    = StringToDouble(parts[17]);
   if(g_lots<=0.0)
      g_lots = InpFbLots;
   g_synced = true;
  }

void ExecuteCommand(string &parts[])
  {
   int n = ArraySize(parts);
   if(n<4)
      return;
   string id   = parts[1];
   string kind = parts[2];
   string arg  = parts[3];
   double lots = (n>4 ? StringToDouble(parts[4]) : 0.0);

   if(!InpAllowTrade)
     {
      Acknowledge(id,"blocked-terminal");
      return;
     }

   if(kind=="OPEN")
     {
      bool isBuy = (arg=="BUY");
      bool ok = OpenTrade(isBuy,lots);
      Acknowledge(id,(ok ? "opened "+arg : "error "+(string)trade.ResultRetcode()));
      return;
     }
   if(kind=="CLOSE")
     {
      int dir = 0;
      if(arg=="BUY")
         dir = 1;
      if(arg=="SELL")
         dir = -1;
      int closed = ClosePositions(dir);
      Acknowledge(id,"closed "+(string)closed);
      return;
     }
   Acknowledge(id,"unknown-command");
  }

void HandleResponse(string response)
  {
   StringReplace(response,"\r","");
   string lines[];
   int count = StringSplit(response,(ushort)10,lines);
   for(int i=0; i<count; i++)
     {
      if(StringLen(lines[i])<3)
         continue;
      string parts[];
      int fields = StringSplit(lines[i],(ushort)124,parts);
      if(fields<2)
         continue;
      if(parts[0]=="STATUS")
         ApplyStatus(parts);
      else
         if(parts[0]=="CMD")
            ExecuteCommand(parts);
         else
            if(parts[0]=="ERR")
               Print("Jkinstrading refused the sync: ",lines[i]);
     }
  }

void Sync()
  {
   double closes[];
   ArraySetAsSeries(closes,false);
   int wanted = (int)MathMax(60,MathMin(500,InpBarsToSend));
   int copied = CopyClose(g_symbol,_Period,0,wanted,closes);
   if(copied<10)
     {
      Print("Sync skipped: only ",(string)copied," closes available yet.");
      return;
     }

   string series = "";
   for(int i=0; i<copied; i++)
     {
      if(i>0)
         series += ",";
      series += DoubleToString(closes[i],g_digits);
     }

   datetime bar = (datetime)SeriesInfoInteger(g_symbol,_Period,SERIES_LASTBAR_DATE);
   string body = "key="+UrlEncode(InpApiKey)+
                 "&platform="+UrlEncode("MetaTrader 5")+
                 "&symbol="+UrlEncode(g_symbol)+
                 "&tf="+UrlEncode(TimeframeName())+
                 "&bar="+IntegerToString((long)bar)+
                 "&bid="+DoubleToString(SymbolInfoDouble(g_symbol,SYMBOL_BID),g_digits)+
                 "&ask="+DoubleToString(SymbolInfoDouble(g_symbol,SYMBOL_ASK),g_digits)+
                 "&spread="+IntegerToString((long)SymbolInfoInteger(g_symbol,SYMBOL_SPREAD))+
                 "&balance="+DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE),2)+
                 "&equity="+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2)+
                 "&currency="+UrlEncode(AccountInfoString(ACCOUNT_CURRENCY))+
                 "&buys="+IntegerToString(CountPositions(1))+
                 "&sells="+IntegerToString(CountPositions(-1))+
                 "&floating="+DoubleToString(FloatingProfit(),2)+
                 "&done="+UrlEncode(g_done)+
                 "&closes="+series;

   int    len = StringLen(body);
   char   post[];
   char   result[];
   string resultHeaders;
   ArrayResize(post,len);
   StringToCharArray(body,post,0,len,CP_UTF8);

   ResetLastError();
   int code = WebRequest("POST",g_url+"/api/sync",
                         "Content-Type: application/x-www-form-urlencoded\r\n",
                         5000,post,result,resultHeaders);
   if(code==-1)
     {
      int err = GetLastError();
      Print("WebRequest failed, error ",(string)err,
            ". Allow ",g_url," in Tools > Options > Expert Advisors > Allow WebRequest for listed URL.");
      return;
     }
   if(code!=200)
     {
      Print("Jkinstrading answered HTTP ",(string)code);
      return;
     }

   g_done = "";
   HandleResponse(CharArrayToString(result,0,ArraySize(result),CP_UTF8));
  }

//+------------------------------------------------------------------+
//| Events                                                           |
//+------------------------------------------------------------------+
void OnTimer()
  {
   Sync();
   CleanupGlobals();
  }

void OnTick()
  {
   ManagePositions();
   Comment("Jkinstrading bridge  |  ",g_symbol,
           "  |  robot: ",(g_running ? "RUNNING" : "PAUSED"),
           "  |  synced: ",(g_synced ? "yes" : "no"),
           "  |  lots: ",DoubleToString(g_lots,g_volDigits));
  }
//+------------------------------------------------------------------+

Standalone source · 763 lines

MA50_Cross_EA.mq5

Download file
//+------------------------------------------------------------------+
//|                                                MA50_Cross_EA.mq5 |
//|  Moving-average cross Expert Advisor                             |
//|  - money based SL / TP1 / TP2 / TP3 (separate for BUY and SELL)   |
//|  - partial closes at TP1 and TP2                                 |
//|  - break-even lock and money trailing stop                       |
//|  - stage + original volume kept in terminal GlobalVariables       |
//|  Works on hedging and netting accounts.                          |
//+------------------------------------------------------------------+
#property copyright "MA50_Cross_EA"
#property version   "1.00"
#property description "MA cross EA with dollar SL/TP, three targets, partial closes, break-even lock and dollar trailing."

#include <Trade\Trade.mqh>

//+------------------------------------------------------------------+
//| Enumerations                                                     |
//+------------------------------------------------------------------+
enum ENUM_OPPOSITE_MODE
  {
   OPPOSITE_IGNORE         = 0, // Ignore opposite signal
   OPPOSITE_CLOSE_AND_OPEN = 1  // Close opposite positions, then open
  };

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input group "=== Moving Average ==="
input int                InpMAPeriod     = 50;            // MA period
input ENUM_MA_METHOD     InpMAMethod     = MODE_SMA;      // MA method
input ENUM_APPLIED_PRICE InpMAPrice      = PRICE_CLOSE;   // MA applied price
input bool               InpLive         = false;         // Live bar signals (false = confirm on bar close)

input group "=== Trading ==="
input double             InpLots         = 0.10;          // Lot size
input long               InpMagic        = 505050;        // Magic number
input string             InpComment      = "MA50_Cross";  // Order comment
input bool               InpAllowBuy     = true;          // Allow BUY
input bool               InpAllowSell    = true;          // Allow SELL
input int                InpMaxPositions = 1;             // Max positions (this symbol + magic)
input ENUM_OPPOSITE_MODE InpReverseMode  = OPPOSITE_CLOSE_AND_OPEN; // Opposite signal mode
input int                InpMaxSpread    = 0;             // Max spread in points (0 = off)
input int                InpSlippage     = 30;            // Slippage / deviation in points

input group "=== Trading hours (server time) ==="
input bool               InpUseHours     = false;         // Use trading hours filter
input int                InpStartHour    = 7;             // Start hour 0-23
input int                InpEndHour      = 21;            // End hour 0-23 (overnight supported)

input group "=== BUY money targets (deposit currency, for the lot size above) ==="
input double             InpBuySL        = 20.0;          // BUY stop loss in money (0 = off)
input double             InpBuyTP1       = 10.0;          // BUY target 1 in money (0 = off)
input double             InpBuyTP2       = 20.0;          // BUY target 2 in money (0 = off)
input double             InpBuyTP3       = 40.0;          // BUY target 3 in money (final TP, 0 = off)

input group "=== SELL money targets (deposit currency, for the lot size above) ==="
input double             InpSellSL       = 20.0;          // SELL stop loss in money (0 = off)
input double             InpSellTP1      = 10.0;          // SELL target 1 in money (0 = off)
input double             InpSellTP2      = 20.0;          // SELL target 2 in money (0 = off)
input double             InpSellTP3      = 40.0;          // SELL target 3 in money (final TP, 0 = off)

input group "=== Partial close ==="
input bool               InpUsePartial   = true;          // Enable partial closes
input double             InpPartial1Pct  = 50.0;          // Percent of original lots closed at TP1
input double             InpPartial2Pct  = 25.0;          // Percent of original lots closed at TP2

input group "=== Secure profit: break-even lock ==="
input bool               InpUseBreakEven = true;          // Enable break-even lock
input double             InpBETrigger    = 8.0;           // Floating profit trigger in money
input double             InpBELock       = 2.0;           // Money profit locked by the new SL

input group "=== Secure profit: money trailing ==="
input bool               InpUseTrailing  = true;          // Enable money trailing stop
input double             InpTrailStart   = 15.0;          // Start trailing at this floating profit
input double             InpTrailDist    = 8.0;           // Trail distance in money
input double             InpTrailStep    = 2.0;           // Minimum trailing step in money

input group "=== Stage stop-loss moves ==="
input double             InpLockAfterTP1 = 2.0;           // After TP1: money profit locked above entry

//+------------------------------------------------------------------+
//| Globals                                                          |
//+------------------------------------------------------------------+
CTrade   trade;
int      g_maHandle      = INVALID_HANDLE;
int      g_digits        = 0;
double   g_point         = 0.0;
double   g_volStep       = 0.0;
double   g_volMin        = 0.0;
double   g_volMax        = 0.0;
int      g_volDigits     = 2;
datetime g_lastBar       = 0;
datetime g_lastSignalBar = 0;

//+------------------------------------------------------------------+
//| Expert initialization                                            |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpMAPeriod<1)
     {
      Print("Init error: MA period must be 1 or greater.");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpLots<=0.0)
     {
      Print("Init error: lot size must be greater than zero.");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpStartHour<0 || InpStartHour>23 || InpEndHour<0 || InpEndHour>23)
     {
      Print("Init error: trading hours must be between 0 and 23.");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpPartial1Pct<0.0 || InpPartial1Pct>100.0 || InpPartial2Pct<0.0 || InpPartial2Pct>100.0)
     {
      Print("Init error: partial close percentages must be between 0 and 100.");
      return(INIT_PARAMETERS_INCORRECT);
     }

   g_digits  = (int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
   g_point   = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
   g_volStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   g_volMin  = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   g_volMax  = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);

   if(g_point<=0.0)
      g_point = 1.0/MathPow(10.0,(double)g_digits);
   if(g_volStep<=0.0)
      g_volStep = 0.01;
   if(g_volMin<=0.0)
      g_volMin = g_volStep;
   if(g_volMax<=0.0)
      g_volMax = 100.0;

   g_volDigits = 0;
   double step = g_volStep;
   while(step<1.0 && g_volDigits<8)
     {
      step *= 10.0;
      g_volDigits++;
     }

   g_maHandle = iMA(_Symbol,_Period,InpMAPeriod,0,InpMAMethod,InpMAPrice);
   if(g_maHandle==INVALID_HANDLE)
     {
      Print("Init error: iMA handle could not be created. Error ",(string)GetLastError());
      return(INIT_FAILED);
     }

   trade.SetExpertMagicNumber((ulong)InpMagic);
   trade.SetDeviationInPoints((ulong)MathMax(0,InpSlippage));
   trade.SetTypeFillingBySymbol(_Symbol);
   trade.SetMarginMode();
   trade.LogLevel(LOG_LEVEL_ERRORS);

   g_lastBar       = (datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
   g_lastSignalBar = 0;

   Print("MA50_Cross_EA started on ",_Symbol," ",EnumToString((ENUM_TIMEFRAMES)_Period),
         " magic=",(string)InpMagic," lots=",DoubleToString(InpLots,g_volDigits));
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Expert deinitialization                                          |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(g_maHandle!=INVALID_HANDLE)
     {
      IndicatorRelease(g_maHandle);
      g_maHandle = INVALID_HANDLE;
     }
   Print("MA50_Cross_EA stopped. Reason code ",(string)reason);
  }

//+------------------------------------------------------------------+
//| Global variable helpers (stage + original volume per ticket)      |
//+------------------------------------------------------------------+
string GVPrefix()
  {
   return("MA50EA_"+IntegerToString(InpMagic)+"_");
  }

string GVName(const ulong ticket,const string suffix)
  {
   return(GVPrefix()+IntegerToString((long)ticket)+"_"+suffix);
  }

int PositionStage(const ulong ticket)
  {
   string name = GVName(ticket,"stage");
   if(!GlobalVariableCheck(name))
      return(0);
   return((int)GlobalVariableGet(name));
  }

void SetPositionStage(const ulong ticket,const int stage)
  {
   GlobalVariableSet(GVName(ticket,"stage"),(double)stage);
  }

double OriginalVolume(const ulong ticket,const double currentVolume)
  {
   string name = GVName(ticket,"vol");
   if(!GlobalVariableCheck(name))
     {
      GlobalVariableSet(name,currentVolume);
      return(currentVolume);
     }
   double stored = GlobalVariableGet(name);
   if(stored<=0.0)
     {
      GlobalVariableSet(name,currentVolume);
      return(currentVolume);
     }
   return(stored);
  }

void CleanupGlobals()
  {
   string prefix = GVPrefix();
   int    total  = GlobalVariablesTotal();
   for(int i=total-1; i>=0; i--)
     {
      string name = GlobalVariableName(i);
      if(StringFind(name,prefix)!=0)
         continue;
      string rest = StringSubstr(name,StringLen(prefix));
      int    sep  = StringFind(rest,"_");
      if(sep<=0)
         continue;
      ulong ticket = (ulong)StringToInteger(StringSubstr(rest,0,sep));
      if(ticket==0 || !PositionSelectByTicket(ticket))
         GlobalVariableDel(name);
     }
  }

//+------------------------------------------------------------------+
//| Money / volume helpers                                           |
//+------------------------------------------------------------------+
double MoneyToPrice(const double money,const double volume)
  {
   if(money<=0.0 || volume<=0.0)
      return(0.0);
   double tickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
   double tickSize  = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   if(tickValue<=0.0 || tickSize<=0.0)
      return(0.0);
   double moneyPerPrice = (tickValue/tickSize)*volume;
   if(moneyPerPrice<=0.0)
      return(0.0);
   return(money/moneyPerPrice);
  }

double NormalizeLots(const double volume)
  {
   if(g_volStep<=0.0)
      return(0.0);
   double v = MathFloor(volume/g_volStep+0.5)*g_volStep;
   v = NormalizeDouble(v,g_volDigits);
   if(v<g_volMin)
      v = g_volMin;
   if(v>g_volMax)
      v = g_volMax;
   return(NormalizeDouble(v,g_volDigits));
  }

double FloorLots(const double volume)
  {
   if(g_volStep<=0.0 || volume<=0.0)
      return(0.0);
   double v = MathFloor(volume/g_volStep+0.0000001)*g_volStep;
   return(NormalizeDouble(v,g_volDigits));
  }

//+------------------------------------------------------------------+
//| Market filters                                                   |
//+------------------------------------------------------------------+
bool TimeAllowed()
  {
   if(!InpUseHours)
      return(true);
   MqlDateTime dt;
   if(!TimeToStruct(TimeCurrent(),dt))
      return(false);
   int hour = dt.hour;
   if(InpStartHour==InpEndHour)
      return(true);
   if(InpStartHour<InpEndHour)
      return(hour>=InpStartHour && hour<InpEndHour);
   return(hour>=InpStartHour || hour<InpEndHour);
  }

bool SpreadAllowed()
  {
   if(InpMaxSpread<=0)
      return(true);
   long spread = (long)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
   return(spread<=(long)InpMaxSpread);
  }

double StopsDistance()
  {
   long level = (long)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   if(level<0)
      level = 0;
   return((double)level*g_point);
  }

double FreezeDistance()
  {
   long level = (long)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
   if(level<0)
      level = 0;
   return((double)level*g_point);
  }

bool FreezeBlocks(const bool isBuy,const double currentSL,const double currentTP)
  {
   double freeze = FreezeDistance();
   if(freeze<=0.0)
      return(false);
   double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
   double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   if(isBuy)
     {
      if(currentSL>0.0 && (bid-currentSL)<freeze)
         return(true);
      if(currentTP>0.0 && (currentTP-bid)<freeze)
         return(true);
      return(false);
     }
   if(currentSL>0.0 && (currentSL-ask)<freeze)
      return(true);
   if(currentTP>0.0 && (ask-currentTP)<freeze)
      return(true);
   return(false);
  }

void AdjustStops(const bool isBuy,double &sl,double &tp)
  {
   double minDist = StopsDistance();
   double bid     = SymbolInfoDouble(_Symbol,SYMBOL_BID);
   double ask     = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   if(isBuy)
     {
      if(sl>0.0 && sl>(bid-minDist))
         sl = bid-minDist;
      if(tp>0.0 && tp<(ask+minDist))
         tp = ask+minDist;
     }
   else
     {
      if(sl>0.0 && sl<(ask+minDist))
         sl = ask+minDist;
      if(tp>0.0 && tp>(bid-minDist))
         tp = bid-minDist;
     }
   if(sl<0.0)
      sl = 0.0;
   if(tp<0.0)
      tp = 0.0;
   if(sl>0.0)
      sl = NormalizeDouble(sl,g_digits);
   if(tp>0.0)
      tp = NormalizeDouble(tp,g_digits);
  }

//+------------------------------------------------------------------+
//| Signal                                                           |
//+------------------------------------------------------------------+
bool GetSignal(int &direction)
  {
   direction = 0;
   int shift  = (InpLive ? 0 : 1);
   int needed = shift+2;

   double ma[];
   double close[];
   ArraySetAsSeries(ma,true);
   ArraySetAsSeries(close,true);

   int copiedMA    = CopyBuffer(g_maHandle,0,0,needed,ma);
   int copiedClose = CopyClose(_Symbol,_Period,0,needed,close);
   if(copiedMA<needed || copiedClose<needed)
      return(false);

   double maSignal   = ma[shift];
   double maPrevious = ma[shift+1];
   double cSignal    = close[shift];
   double cPrevious  = close[shift+1];
   if(maSignal<=0.0 || maPrevious<=0.0)
      return(false);

   if(cPrevious<=maPrevious && cSignal>maSignal)
     {
      direction = 1;
      return(true);
     }
   if(cPrevious>=maPrevious && cSignal<maSignal)
     {
      direction = -1;
      return(true);
     }
   return(false);
  }

//+------------------------------------------------------------------+
//| Position counting / closing                                      |
//+------------------------------------------------------------------+
int CountPositions(const int direction)
  {
   int count = 0;
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      long type = PositionGetInteger(POSITION_TYPE);
      if(direction>0 && type!=(long)POSITION_TYPE_BUY)
         continue;
      if(direction<0 && type!=(long)POSITION_TYPE_SELL)
         continue;
      count++;
     }
   return(count);
  }

void CloseOpposite(const int direction)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      long type   = PositionGetInteger(POSITION_TYPE);
      bool isBuy  = (type==(long)POSITION_TYPE_BUY);
      if(direction>0 && isBuy)
         continue;
      if(direction<0 && !isBuy)
         continue;
      if(FreezeBlocks(isBuy,PositionGetDouble(POSITION_SL),PositionGetDouble(POSITION_TP)))
         continue;
      if(!trade.PositionClose(ticket))
         Print("Close opposite failed, ticket ",(string)ticket,
               " retcode=",(string)trade.ResultRetcode()," ",trade.ResultRetcodeDescription());
      else
        {
         GlobalVariableDel(GVName(ticket,"stage"));
         GlobalVariableDel(GVName(ticket,"vol"));
        }
     }
  }

//+------------------------------------------------------------------+
//| Open a new trade                                                 |
//+------------------------------------------------------------------+
bool OpenTrade(const int direction)
  {
   double lots = NormalizeLots(InpLots);
   if(lots<=0.0)
     {
      Print("Open skipped: lot size could not be normalized.");
      return(false);
     }

   bool   isBuy = (direction>0);
   double price = (isBuy ? SymbolInfoDouble(_Symbol,SYMBOL_ASK) : SymbolInfoDouble(_Symbol,SYMBOL_BID));
   if(price<=0.0)
      return(false);

   double slMoney = (isBuy ? InpBuySL  : InpSellSL);
   double tpMoney = (isBuy ? InpBuyTP3 : InpSellTP3);
   double slDist  = MoneyToPrice(slMoney,lots);
   double tpDist  = MoneyToPrice(tpMoney,lots);

   double sl = 0.0;
   double tp = 0.0;
   if(slDist>0.0)
      sl = (isBuy ? price-slDist : price+slDist);
   if(tpDist>0.0)
      tp = (isBuy ? price+tpDist : price-tpDist);
   AdjustStops(isBuy,sl,tp);

   bool ok = false;
   if(isBuy)
      ok = trade.Buy(lots,_Symbol,0.0,sl,tp,InpComment);
   else
      ok = trade.Sell(lots,_Symbol,0.0,sl,tp,InpComment);

   if(!ok)
     {
      Print("Open ",(isBuy ? "BUY" : "SELL")," failed, retcode=",(string)trade.ResultRetcode(),
            " ",trade.ResultRetcodeDescription());
      return(false);
     }

   ulong dealTicket = (ulong)trade.ResultOrder();
   Print("Opened ",(isBuy ? "BUY" : "SELL")," ",DoubleToString(lots,g_volDigits),
         " lots at ",DoubleToString(trade.ResultPrice(),g_digits),
         " order ",(string)dealTicket,
         " SL ",DoubleToString(sl,g_digits)," TP ",DoubleToString(tp,g_digits));
   return(true);
  }

//+------------------------------------------------------------------+
//| Stop-loss move (favorable direction only)                        |
//+------------------------------------------------------------------+
bool MoveStopLoss(const ulong ticket,const bool isBuy,double newSL,
                  double &currentSL,const double currentTP)
  {
   if(newSL<=0.0)
      return(false);
   newSL = NormalizeDouble(newSL,g_digits);
   double tolerance = g_point*0.5;

   if(isBuy && currentSL>0.0 && newSL<=(currentSL+tolerance))
      return(false);
   if(!isBuy && currentSL>0.0 && newSL>=(currentSL-tolerance))
      return(false);

   double minDist = StopsDistance();
   double bid     = SymbolInfoDouble(_Symbol,SYMBOL_BID);
   double ask     = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
   if(isBuy && newSL>(bid-minDist))
      return(false);
   if(!isBuy && newSL<(ask+minDist))
      return(false);
   if(FreezeBlocks(isBuy,currentSL,currentTP))
      return(false);

   double tp = (currentTP>0.0 ? NormalizeDouble(currentTP,g_digits) : 0.0);
   if(!trade.PositionModify(ticket,newSL,tp))
     {
      Print("Modify SL failed, ticket ",(string)ticket,
            " newSL=",DoubleToString(newSL,g_digits),
            " retcode=",(string)trade.ResultRetcode()," ",trade.ResultRetcodeDescription());
      return(false);
     }
   currentSL = newSL;
   return(true);
  }

//+------------------------------------------------------------------+
//| Partial close                                                    |
//+------------------------------------------------------------------+
void ClosePartial(const ulong ticket,const double originalVolume,
                  const double currentVolume,const double percent)
  {
   if(percent<=0.0 || currentVolume<=0.0)
      return;
   double want = FloorLots(originalVolume*percent/100.0);
   if(want<=0.0)
      return;
   if(want>(currentVolume-g_volStep*0.5))
      want = FloorLots(currentVolume-g_volStep);
   if(want<g_volMin-0.0000001)
      return;
   if((currentVolume-want)<(g_volMin-0.0000001))
      return;
   if(!trade.PositionClosePartial(ticket,want))
      Print("Partial close failed, ticket ",(string)ticket,
            " volume=",DoubleToString(want,g_volDigits),
            " retcode=",(string)trade.ResultRetcode()," ",trade.ResultRetcodeDescription());
   else
      Print("Partial close ",DoubleToString(want,g_volDigits)," lots on ticket ",(string)ticket);
  }

//+------------------------------------------------------------------+
//| Target helpers                                                   |
//+------------------------------------------------------------------+
double TargetPrice(const double entry,const bool isBuy,const double money,const double volume)
  {
   double dist = MoneyToPrice(money,volume);
   if(dist<=0.0)
      return(0.0);
   return(NormalizeDouble(isBuy ? entry+dist : entry-dist,g_digits));
  }

bool TargetReached(const bool isBuy,const double marketPrice,const double target)
  {
   if(target<=0.0)
      return(false);
   if(isBuy)
      return(marketPrice>=target);
   return(marketPrice<=target);
  }

//+------------------------------------------------------------------+
//| Manage open positions (every tick)                               |
//+------------------------------------------------------------------+
void ManagePositions()
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
     {
      ulong ticket = PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(!PositionSelectByTicket(ticket))
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if(PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;

      long   type      = PositionGetInteger(POSITION_TYPE);
      bool   isBuy     = (type==(long)POSITION_TYPE_BUY);
      double curVol    = PositionGetDouble(POSITION_VOLUME);
      double entry     = PositionGetDouble(POSITION_PRICE_OPEN);
      double curSL     = PositionGetDouble(POSITION_SL);
      double curTP     = PositionGetDouble(POSITION_TP);
      double profit    = PositionGetDouble(POSITION_PROFIT);
      double bid       = SymbolInfoDouble(_Symbol,SYMBOL_BID);
      double ask       = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
      double market    = (isBuy ? bid : ask);
      if(curVol<=0.0 || entry<=0.0 || market<=0.0)
         continue;

      double origVol   = OriginalVolume(ticket,curVol);
      int    stage     = PositionStage(ticket);
      double tp1Money  = (isBuy ? InpBuyTP1 : InpSellTP1);
      double tp2Money  = (isBuy ? InpBuyTP2 : InpSellTP2);
      double tp1Price  = TargetPrice(entry,isBuy,tp1Money,origVol);
      double tp2Price  = TargetPrice(entry,isBuy,tp2Money,origVol);

      //--- first target: partial close + lock money above entry
      if(stage<1 && TargetReached(isBuy,market,tp1Price))
        {
         if(InpUsePartial)
            ClosePartial(ticket,origVol,curVol,InpPartial1Pct);
         SetPositionStage(ticket,1);
         double lockDist = MoneyToPrice(InpLockAfterTP1,origVol);
         if(lockDist>0.0)
            MoveStopLoss(ticket,isBuy,(isBuy ? entry+lockDist : entry-lockDist),curSL,curTP);
         continue;
        }

      //--- second target: partial close + SL to the TP1 level
      if(stage==1 && TargetReached(isBuy,market,tp2Price))
        {
         if(InpUsePartial)
            ClosePartial(ticket,origVol,curVol,InpPartial2Pct);
         SetPositionStage(ticket,2);
         double anchor = (tp1Price>0.0 ? tp1Price : entry);
         MoveStopLoss(ticket,isBuy,anchor,curSL,curTP);
         continue;
        }

      //--- break-even / money lock
      if(InpUseBreakEven && InpBETrigger>0.0 && profit>=InpBETrigger)
        {
         double lockDist = MoneyToPrice(InpBELock,curVol);
         double target   = (isBuy ? entry+lockDist : entry-lockDist);
         if(InpBELock<=0.0)
            target = entry;
         MoveStopLoss(ticket,isBuy,target,curSL,curTP);
        }

      //--- money trailing stop
      if(InpUseTrailing && InpTrailDist>0.0 && profit>=InpTrailStart)
        {
         double trailDist = MoneyToPrice(InpTrailDist,curVol);
         double stepDist  = MoneyToPrice(InpTrailStep,curVol);
         if(trailDist>0.0)
           {
            double candidate = (isBuy ? market-trailDist : market+trailDist);
            bool   improves  = true;
            if(curSL>0.0 && stepDist>0.0)
              {
               if(isBuy)
                  improves = (candidate-curSL)>=stepDist;
               else
                  improves = (curSL-candidate)>=stepDist;
              }
            if(improves)
               MoveStopLoss(ticket,isBuy,candidate,curSL,curTP);
           }
        }
     }
  }

//+------------------------------------------------------------------+
//| Signal execution                                                 |
//+------------------------------------------------------------------+
void ProcessSignal(const int direction)
  {
   if(direction>0 && !InpAllowBuy)
      return;
   if(direction<0 && !InpAllowSell)
      return;
   if(!TimeAllowed())
      return;
   if(!SpreadAllowed())
      return;

   int opposite = CountPositions(direction>0 ? -1 : 1);
   if(opposite>0)
     {
      if(InpReverseMode==OPPOSITE_IGNORE)
         return;
      CloseOpposite(direction);
     }

   int same = CountPositions(direction);
   if(InpMaxPositions>0 && same>=InpMaxPositions)
      return;
   int total = CountPositions(0);
   if(InpMaxPositions>0 && total>=InpMaxPositions && opposite<=0)
      return;

   OpenTrade(direction);
  }

//+------------------------------------------------------------------+
//| Tick                                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(g_maHandle==INVALID_HANDLE)
      return;

   ManagePositions();

   datetime currentBar = (datetime)SeriesInfoInteger(_Symbol,_Period,SERIES_LASTBAR_DATE);
   bool     isNewBar   = (currentBar!=g_lastBar);
   if(isNewBar)
     {
      g_lastBar = currentBar;
      CleanupGlobals();
     }

   if(!InpLive && !isNewBar)
      return;
   if(InpLive && g_lastSignalBar==currentBar)
      return;

   int direction = 0;
   if(!GetSignal(direction))
      return;
   if(direction==0)
      return;

   if(InpLive)
      g_lastSignalBar = currentBar;

   ProcessSignal(direction);
  }
//+------------------------------------------------------------------+

Assumptions behind the money management