Введение

Особенно в таких высоковолатильных парах, как 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
//+------------------------------------------------------------------+
//|                                  Copyright 2026, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//| PositionSizeCalculatorUSDTRY.mq5                                 |
//+------------------------------------------------------------------+

//--- 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()
     {
      
      // Broker Stop Out Level (%10)
      double stopOutLevel = 10;
      
      // 1 pip = 0.0001 (for 4-digit pairs like USDTRY)
      double pipSize = 0.0001;
      double pips = 0;
      double spread = 0;        
      
      // Position Size (USD based)
      // Order size (e.g., 1.00 lot)
      // Contract Size → Contract size for 1 lot (usually 100,000 in Forex)
      double positionSize = m_lot * m_contractSize;
      
      // Floating P/ L → profit / loss arising from price movement.
      double profit = 0;
      
      double pipValue = 0;
      
      if (m_orderType == "BUY")
      {
          spread = m_openPrice - m_currentPrice;
          pips = spread / pipSize;
          pipValue = (positionSize * pipSize) / m_currentPrice;      
          profit = -((spread * positionSize) / m_currentPrice); // The USD value of 1 pip.
          //profit = -(pips * pipValue); 
      }
      else if (m_orderType == "SELL")
      {
          spread = m_currentPrice - m_openPrice;
          pips = spread / pipSize;
          pipValue = (positionSize * pipSize) / m_currentPrice;
          profit = -((spread * positionSize) / m_currentPrice);
          //profit = -(pips * pipValue); 
      }
             
      // Equity
      double equity = m_balance + profit - m_commission + m_swap;
      
      // Margin
      double margin = positionSize / m_leverage;
      
      // Free Margin
      double freeMargin = equity - margin;
      
      // Margin Level
      double marginLevel = margin > 0 ? (equity / margin) * 100 : 0;
      
      // Stop Out Equity Threshold
      double stopOutEquity = (margin * stopOutLevel) / 100;

      // === Output in Experts ===
      Print("=== Account Position Report (USDTRY v1.0.5-beta) ===");            
      Print("Balance      : ",DoubleToString(m_balance,2)," USD");      
      Print("Equity       : ",DoubleToString(equity,2)," USD");      
      Print("Margin       : ",DoubleToString(margin,2)," USD");
      Print("Free Margin  : ",DoubleToString(freeMargin,2)," USD");
      Print("Margin Level : ",DoubleToString(marginLevel,2)," %");
      Print("Frofit       : ",DoubleToString(profit,2)," USD");
      Print("Spread       : ",DoubleToString(spread,4)," → ",DoubleToString(pips,1)," pips");
      Print("Stop Out Lvl : ",DoubleToString(stopOutLevel,2),"% → Equity Threshold = ",DoubleToString(stopOutEquity,2)," USD");

      // === Output on Chart ===
      int y = 55;
      int step = 80;
      
      // Background box
      DrawBackground("bgReport",10,40,1300,950,clrBlack);
      
      // Title
      DrawLabel("lblHeader",20,y,"=== Account Position Report (USDTRY v1.0.6-beta) ===",14,clrYellow); 
      y+=step;
      
      // Symbol + Order Info
      DrawLabel("lblSymbol",20,y,m_symbol + " - " + m_orderType + " - " + DoubleToString(m_lot,2) +" lot - "+ DoubleToString(m_openPrice, 4),14,clrWhite); 
      y+=step;
      
      // Balance
      DrawLabel("lblBalance",20,y,"Balance : "+DoubleToString(m_balance,2)+" USD",14,clrWhite); 
      y+=step;
      
      // Equity
      DrawLabel("lblEquity",20,y,"Equity : "+DoubleToString(equity,2)+" USD",14,clrWhite); 
      y+=step;
      
      // Margin
      DrawLabel("lblMargin",20,y,"Margin : "+DoubleToString(margin,2)+" USD",14,clrWhite); 
      y+=step;
      
      // Free Margin
      DrawLabel("lblFreeMargin",20,y,"Free Margin : "+DoubleToString(freeMargin,2)+" USD",14,clrWhite); 
      y+=step;
      
      // Margin Level
      DrawLabel("lblMarginLevel",20,y,"Margin Level : "+DoubleToString(marginLevel,2)+" %",14,clrWhite); 
      y+=step;
      
      // Profit / Floating P/L
      color profitColor = (profit >= 0 ? clrGreen : clrRed);
      DrawLabel("lblProfit",20,y,"Profit P/L : "+DoubleToString(profit,2)+" USD",14,profitColor); 
      y+=step;
      
      // Spread
      DrawLabel("lblSpread",20,y,"Spread : "+DoubleToString(spread,5),14,clrWhite); 
      y+=step;
      
      // Spread (pips)
      DrawLabel("lblPips",20,y,"Spread (pips) : "+DoubleToString(pips,2)+" - "+DoubleToString(pipValue,2)+" USD per pip",14,clrWhite); 
      y+=step;
      
      // Stop Out Level
      DrawLabel("lblStopOut",20,y,"Stop Out Lvl : "+DoubleToString(stopOutLevel,2)+"% → Equity Threshold = "+DoubleToString(stopOutEquity,2)+" USD",14,clrWhite); 
      //y+=step;
      
      // SL / TP
      //DrawLabel("lblSL",20,y,"Stop Loss      : "+DoubleToString(stopLoss,2),14,clrBlue); 
      //y+=step;
      
      //DrawLabel("lblTP",20,y,"Take Profit    : "+DoubleToString(takeProfit,2),14,clrBlue); 
      //y+=step;
      
      // Commission & Swap
      //DrawLabel("lblCommission",20,y,"Commission     : "+DoubleToString(m_commission,2)+" USD",14,clrWhite); 
      //y+=step;
      
      //DrawLabel("lblSwap",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‑скрипт, который корректно отражает позиции по счёту.

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

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

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