#define MAGICMA 20050623 //定义的一个常量,作为后面用到的标识符
extern double Lots =0.1;
extern double MaximumRisk =0.02;//最大的风险系数
extern double DecreaseFactor =3;
extern double MovingPeriod =12;
extern double MovingShift =6;
//+------------------------------------------------------------------+
//| 循环查询当前持仓的状态 |
//+------------------------------------------------------------------+
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()
{
double lot=Lots;
int orders=HistoryTotal();
int losses=0;
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk);
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) {Print("Error in history");break;} //查询每一个订单的内容
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue; //判断是否是当前的订单
//---
if(OrderProfit()>0) break; //查询点点是赢还是亏,大于0是赢
if(OrderProfit()<0) losses++; //查询点点是赢还是亏
}
if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
}
//-----------
if(lot<0.1) lot=0.1;
return(lot);
}
//+------------------------------------------------------------------+
//| 检查是否该入场了
//+------------------------------------------------------------------+
void CheckForOpen()
{
double ma;
int res;
if(Volume[0]>1) return;
ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_Close,0);
if(Open[1]>ma && Close[1]<ma)
{
res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
return;
}
if(Open[1]<ma && Close[1]>ma)
{
res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
return;
}
}
void CheckForClose()
{
//---
double ma;
if(Volume[0]>1) return;
ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
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[1]>ma && Close[1]<ma) OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
break;
}
if(OrderType()==OP_SELL)
{
if(Open[1]<ma && Close[1]>ma) OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
break;
}
//----
}
//---
}
void start()
{
//----
if(Bars<100 || IsTradeAllowed()==false) return;
//----
if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
else CheckForClose();
//----
}
//+------------------------------------------------------------------+