#define VOLUME 1.0 // 订单交易量
#define DEVIATION 100 // 平仓价格之前的点数
//+------------------------------------------------------------------+
//| 脚本程序起始函数 |
//+------------------------------------------------------------------+
void OnStart()
{
string currency_profit=SymbolInfoString(_Symbol,SYMBOL_CURRENCY_PROFIT); // 利润货币
double close_price=ChartPriceOnDropped(); // 价格坐标, 对应着使用鼠标拖曳脚本的点位, 用于平仓价格
//---
for(int i=0; i<=ORDER_TYPE_SELL; i++)
{
ENUM_ORDER_TYPE order_type=(ENUM_ORDER_TYPE)i; // 订单类型: 0 - 买, 1 - 卖
double open_price=PriceOpenByOrderType(_Symbol, order_type); // 下单价格: 对于买 - Ask, 对于卖 - Bid
//--- 如果未获得开单价格, 继续循环
if(open_price==0)
continue;
//--- 如果平仓价格为0 (脚本不是通过拖曳到图表上而运行的), 计算价格
if(close_price==0)
close_price=(order_type==ORDER_TYPE_BUY ? open_price + DEVIATION * _Point : open_price - DEVIATION * _Point);
//--- 根据传入的参数计算当前账户和市场环境下的利润大小
double profit=0;
ResetLastError();
if(!OrderCalcProfit(order_type, _Symbol, VOLUME, open_price, close_price, profit))
{
Print("OrderCalcProfit() failed. Error ", GetLastError());
continue;
}
//--- 在日志中打印收到的利润值
PrintFormat("Estimated profit for %.2f %s position on %s with opening price of %.*f and closing price of %.*f: %.2f %s",
VOLUME, OrderTypeDescription(order_type), _Symbol, _Digits, open_price, _Digits, close_price, profit, currency_profit);
}
/*
结果:
Estimated profit for 1.00 Buy position on EURUSD with opening price of 1.10757 and closing price of 1.10881: 124.00 USD
Estimated profit for 1.00 Sell position on EURUSD with opening price of 1.10753 and closing price of 1.10881: -128.00 USD
*/
}
//+------------------------------------------------------------------+
//| 根据订单类型返回开单价格 |
//+------------------------------------------------------------------+
double PriceOpenByOrderType(const string symbol, const ENUM_ORDER_TYPE order_type)
{
MqlTick tick={};
//--- 取得交易品种的最新价格
if(!SymbolInfoTick(symbol, tick))
{
Print("SymbolInfoTick() failed. Error ", GetLastError());
return 0;
}
//--- 返回根据订单类型的价格
switch(order_type)
{
case ORDER_TYPE_BUY : return(tick.ask);
case ORDER_TYPE_SELL : return(tick.bid);
default : return(0);
}
}
//+------------------------------------------------------------------+
//| 返回订单类型的描述 |
//+------------------------------------------------------------------+
string OrderTypeDescription(const ENUM_ORDER_TYPE order_type)
{
switch(order_type)
{
case ORDER_TYPE_BUY : return("Buy");
case ORDER_TYPE_SELL : return("Sell");
default : return("Unknown order type");
}
}
|