写程序应该多多使用函数,这样能够提高编程的效率,下面是曾经用到的函数,将他们保存下来,供以后直接复制过去使用,这就不必每次都要重写了。
//---显示信息函数,因为创建了两个对象,所以在退出时,应该删除对象-----------------
void showinfo(){
ObjectCreate("p1",OBJ_LABEL,0,0,0);
ObjectSetText("p1",Symbol()+" 帐户余额:"+DoubleToStr(AccountBalance(),0)+" 帐户净值:"+DoubleToStr(AccountEquity(),0),18,"华文细黑",Yellow);
ObjectSet("p1",OBJPROP_XDISTANCE,10);
ObjectSet("p1",OBJPROP_YDISTANCE,40);
ObjectCreate("p2",OBJ_LABEL,0,0,0);
ObjectSetText("p2","EA-yunkaicn 自动交易系统已经启动。时间:"+Month()+"月"+Day()+"日"+Hour()+"点"+Minute()+"分",18,"华文细黑",Yellow);
ObjectSet("p2",OBJPROP_XDISTANCE,10);
ObjectSet("p2",OBJPROP_YDISTANCE,10);
}
//---计算当前货币订单数函数。
int CalculateCurrentOrders(string symbol)
{
int buys=0,sells=0;
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
{
if(OrderType()==OP_BUY) buys++;
if(OrderType()==OP_SELL) sells++;
}
}
if(buys>0) return(buys);
else return(-sells);
}
//---计算交易手数的函数。
double LotsOptimized()
{
if(AccountEquity()<300) return(0.1);
if(AccountEquity()>=300 && AccountEquity()<500) return(0.2);
if(AccountEquity()>=500 && AccountEquity()<1000) return(0.4);
if(AccountEquity()>=1000 && AccountEquity()<5000) return(0.6);
if(AccountEquity()>=5000 && AccountEquity()<10000) return(1);
if(AccountEquity()>=10000) return(5);
}
//---开仓函数。
void CheckForOpen()
{
Lots=0.1;
if(zo<minfan && ccip1<-ccipt && ccip2>=-ccipt)
{
res=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid + StopLoss*Point,Bid - TakeProfit*Point,"",MAGICMA,0,Red);
if(res>0)
{
if(OrderSelect(res,SELECT_BY_TICKET,MODE_TRADES))
Alert(Symbol(),"卖单已经开了,价格是:",OrderOpenPrice());
}
else Alert(Symbol(),"卖单开仓出错:",ErrorDescription(GetLastError()));
return;
return;
}
if(zo>maxfan && ccip1>ccipt && ccip2<=ccipt)
{
res=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask - StopLoss*Point, Ask + TakeProfit*Point,"",MAGICMA, 0, Red);
if(res>0)
{
if(OrderSelect(res,SELECT_BY_TICKET,MODE_TRADES))
Alert(Symbol(),"买单已经开了,价格是:",OrderOpenPrice());
}
else Alert(Symbol(),"买单开仓出错:",ErrorDescription(GetLastError()));
return;
}
}
//---平仓函数。
void CheckForClose()
{
Print("当前订单的利润:",OrderProfit(),"当前交易量(手):",LotsOptimized());
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
if(OrderType()==OP_BUY)
{
if(Open[3]>=Close[3] && Open[2]>=Close[2] && Open[1]>=Close[1] )
OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
}
if(OrderType()==OP_SELL)
{
if(Open[3]<=Close[3] && Open[2]<=Close[2] && Open[1]<=Close[1] )
OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
}
}
}