Введение

Особенно в таких высоковолатильных парах, как USDTRY, неверно рассчитанные значения Equity, Margin, Free Margin и Margin Level могут ввести инвестора в заблуждение и ослабить управление рисками.

Эта статья рассматривает разработку Account Position Calculator, который позволяет инвесторам прозрачно и точно отслеживать свои позиции.

  • Выполняет расчёт размера позиции, маржи и плавающей прибыли/убытка (floating P/L) по формулам.
  • Автоматически отображает значения Equity, Free Margin и Margin Level.
  • Показывает результаты как в USD, так и в TRY, обеспечивая двухвалютное отслеживание.
  • Благодаря модульной структуре кода легко применяется как в сценариях BUY, так и SELL.
  • Дополнительно интегрирована логика Stop Out Level, которая информирует инвестора о пороге риска.

Создадим новый класс CAccountPositionCalculator.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//+------------------------------------------------------------------+
//|                                  Copyright 2026, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+

//--- Helper function: draw text on chart
void DrawLabel(string name,int x,int y,string text,int fontSize,color clr)
  {
   if(ObjectFind(0,name) == -1)
      ObjectCreate(0,name,OBJ_LABEL,0,0,0);

   ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_FONTSIZE,fontSize);
   ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
   ObjectSetString(0,name,OBJPROP_TEXT,text);
  }

//--- Helper function: background for report block
void DrawBackground(string name,int x,int y,int width,int height,color clr)
  {
   if(ObjectFind(0,name) == -1)
      ObjectCreate(0,name,OBJ_RECTANGLE_LABEL,0,0,0);

   ObjectSetInteger(0,name,OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x);
   ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y);
   ObjectSetInteger(0,name,OBJPROP_XSIZE,width);
   ObjectSetInteger(0,name,OBJPROP_YSIZE,height);
   ObjectSetInteger(0,name,OBJPROP_BGCOLOR,clr);
   ObjectSetInteger(0,name,OBJPROP_COLOR,clr);
   ObjectSetInteger(0,name,OBJPROP_STYLE,STYLE_SOLID);
   ObjectSetInteger(0,name,OBJPROP_WIDTH,0);
   ObjectSetString(0,name,OBJPROP_TEXT,"");
  }

//--- Position Calculator
class CAccountPositionCalculator
  {
private:
   // Account information
   double m_balance;   
   double m_equity;
   double m_contractSize;
   double m_leverage;
   
   // Order information
   string m_orderType;
   string m_symbol;
   double m_lot;
   double m_openPrice;
   double m_currentPrice;
   double m_stopLoss;
   double m_takeProfit;
   double m_commission;
   double m_swap;

public:   
   CAccountPositionCalculator(
      double bal, 
      double cSize, 
      double lev,
      string oType,
      string sym,
      double l,
      double oPrice,
      double cPrice,
      double sL,
      double tP,
      double comm,
      double sw
   )
     {
      m_balance      = bal;  
      m_equity       = bal;      
      m_contractSize = cSize;
      m_leverage     = lev;

      m_orderType    = oType;
      m_symbol       = sym;
      m_lot          = l;
      m_openPrice    = oPrice;
      m_currentPrice = cPrice;
      m_stopLoss     = sL;
      m_takeProfit   = tP;
      m_commission   = comm;
      m_swap         = sw;
     }

   void Report()
     {
      
      // 1 pip = 0.0001 (for 4-digit pairs like USDTRY)
      double pipSize = 0.0001;

      // Broker Stop Out Level (%10)
      double stopOutLevel = 10;

      // Floating P/L in TRY
      double floatingPL_TRY = 0.0;

      if (m_orderType == "BUY")
      {          
          floatingPL_TRY = (m_currentPrice - m_openPrice) * m_contractSize * m_lot;
      }
      else if (m_orderType == "SELL")
      {       
          floatingPL_TRY = (m_openPrice - m_currentPrice) * m_contractSize * m_lot;
      }

      // Floating P/L in USD
      double floatingPL_USD = floatingPL_TRY / m_currentPrice;

      // Equity = Balance + Floating P/L - Commission + Swap
      m_equity = m_balance + floatingPL_USD - m_commission + m_swap;      
      
      // Margin in USD
      double marginUSD = (m_contractSize * m_lot) / m_leverage;
      
      // Free Margin
      double freeMargin = m_equity - marginUSD;

      // Margin Level
      double marginLevel = marginUSD > 0 ? (m_equity / marginUSD) * 100 : 0;

      // Spread Cost
      double spreadCost = 0;
      double spreadCost_TRY = 0;      
      
      if (m_orderType == "BUY")
      {          
          spreadCost = (m_currentPrice - m_openPrice);
      }
      else if (m_orderType == "SELL")
      {
          spreadCost = (m_openPrice - m_currentPrice);
      }      
            
      //Pip Size
      double pips = spreadCost / pipSize;
      
      // Spread Cost in TRY
      spreadCost_TRY = spreadCost * m_contractSize * m_lot;
      
      //Print("spreadCost : ", spreadCost , " - m_contractSize : ", m_contractSize, " - m_lot : ", m_lot);
      //Print("spreadCost_TRY : ", spreadCost_TRY);
      
      // Profit in USD
      double spreadCost_USD = spreadCost_TRY / m_currentPrice;

      // Stop Out Equity Threshold
      double stopOutEquity = (marginUSD * stopOutLevel) / 100;
      
      if (m_equity <= stopOutEquity)
      {         
         Print("️STOP OUT RISK");
      }

      // === Output in Experts ===
      Print("=== Position Report (USDTRY v1.0.2-beta) ===");
      Print("Symbol : ", m_symbol, " - Type : ", m_orderType ," - Size : ", m_lot, " - Open Price : ", m_openPrice, " - Current Price : ",m_currentPrice);
      Print("Balance       : ",DoubleToString(m_balance,2)," USD");
      Print("Equity        : ",DoubleToString(m_equity,2)," USD");
      //Print("Margin      : ",DoubleToString(marginTRY,2)," TRY - ",DoubleToString(marginUSD,2)," USD");
      Print("Margin        : ",DoubleToString(marginUSD,2)," USD");
      Print("Free Margin   : ",DoubleToString(freeMargin,2)," USD");
      Print("Margin Level  : ",DoubleToString(marginLevel,2),"%");
      Print("Pips          : ",DoubleToString(pips, 4));
      Print("Profit        : ",DoubleToString(spreadCost_TRY,2), "TRY - ", DoubleToString(spreadCost_USD,2)," USD");
      //Print("Floating P/L  : ",DoubleToString(floatingPL_USD,2)," USD");
      Print("Stop Out Lvl  : ",DoubleToString(stopOutLevel,2),"% / Equity Threshold = ",DoubleToString(stopOutEquity,2)," USD");      
      Print("Stop Loss     : ",DoubleToString(m_stopLoss,2)," USD");
      Print("Take Profit   : ",DoubleToString(m_takeProfit,2)," USD");
      Print("Commission    : ",DoubleToString(m_commission,2)," USD");
      Print("Swap          : ",DoubleToString(m_swap,2)," USD");


      // === Output on Chart ===
      int y = 55;
      int step = 65;

      DrawBackground("bgReport",10,40,1800,1000,clrBlack);

      DrawLabel("lbl1",20,y,"=== Position Report (USDTRY v1.0.2-beta) ===",14,clrYellow); y+=step;
      DrawLabel("lbl2",20,y,m_symbol + " - " + m_orderType + " - " + DoubleToString(m_lot,2) +" - "+ DoubleToString(m_openPrice, 5),14,clrWhite); y+=step;      
      DrawLabel("lbl4",20,y,"Balance            : "+DoubleToString(m_balance,2)+" USD",14,clrWhite); y+=step;
      DrawLabel("lbl5",20,y,"Equity             : "+DoubleToString(m_equity,2)+" USD",14,clrGreen); y+=step;   
      DrawLabel("lbl11",20,y,"Margin            : "+DoubleToString(marginUSD,2)+" USD",14,clrRed); y+=step;       
      DrawLabel("lbl12",20,y,"Free Margin       : "+DoubleToString(freeMargin,2)+" USD",14,clrWhite); y+=step;
      DrawLabel("lbl13",20,y,"Margin Level      : "+DoubleToString(marginLevel,2)+"%",14,clrWhite); y+=step;
      DrawLabel("lbl6",20,y,"Floating P/L       : "+DoubleToString(floatingPL_USD,2)+" USD",14,clrWhite); y+=step;
      DrawLabel("lbl7",20,y,"Stop Loss          : "+DoubleToString(m_stopLoss,2),14,clrBlue); y+=step; 
      DrawLabel("lbl8",20,y,"Take Profit        : "+DoubleToString(m_takeProfit,2),14,clrBlue); y+=step;
      DrawLabel("lbl9",20,y,"Commission         : "+DoubleToString(m_commission,2)+" USD",14,clrWhite); y+=step;
      DrawLabel("lbl10",20,y,"Swap              : "+DoubleToString(m_swap,2)+" USD",14,clrWhite); y+=step;      
     }
  };

//--- Script start
int OnStart()
  {
   double balance    = AccountInfoDouble(ACCOUNT_BALANCE);
   double leverage   = (double)AccountInfoInteger(ACCOUNT_LEVERAGE);   
   
   CAccountPositionCalculator calc(
      balance,    // balance
      100000,     // contract
      leverage,   // leverage
      "BUY",      // order type
      "USDTRY",   // symbol
      1.00,       // lot
      14.8259,    // open price
      14.8189,    // current price
      0.0,        // stop loss
      0.0,        // take profit
      0.0,        // commission
      0.0         // swap
   );

   calc.Report();
   return(0);
  }

Заключение

В случае с USDTRY ты получишь MQL5‑скрипт, который корректно отражает позиции по счёту.

Ты узнаешь, как выполняются расчёты маржи и управления рисками по формулам.

Сможешь адаптировать вывод кода под свои сценарии и обеспечивать прозрачную и надёжную отчётность.

В итоге инвесторы смогут принимать более осознанные решения и эффективнее управлять своими рисками.