Esempio n. 1
0
UINT TradeEntry_01(LPVOID pParam)//交易线程1改版
{
#define NUMLADDER 11
	double ladder_01[NUMLADDER] = {-100,-80,-60,-40,-20,0,20,40,60,80,100};//暂时设11档,一定要正负对称且呈阶梯状,否则逻辑混乱
	int needAmount_01[NUMLADDER] = {5,4,3,2,1,0,-1,-2,-3,-4,-5};//每档对应的持仓数量
	int holdA50_01 = 0;//A50持有数量
	int holdIf_01 = 0;//IF持有数量
	int needHoldA50_01 = 0;//A50应该持有数量
	int needHoldIf_01 = 0;//IF应该持有数量
	int nowLadder_01 = 0;//当前梯级
	bool isFirst = true;//第一次操作
	bool isFilledSectionLeft = false;//本区间左侧目标位的买卖操作是否完成
	bool isFilledSectionRight = false;//本区间右侧目标位的买卖操作是否完成
	int nowSection = 4444;//当前所在的区间,由左端点决定,取4444的初值表示还未找到区间
	if(clientDlg == NULL){
		return -1;
	}
	if(pUserApi == NULL){
		return -1;
	}	
	//从对话框初始化
	datumDiff = clientDlg->m_DeltaDatumDiff + clientDlg->m_datumDiff;
#ifdef _debug 
	holdA50_01 = 50;
#endif
	while(true){
		UpdateTrade.Lock(INFINITE);//事件触发
		//获取系统时间
		SYSTEMTIME sys;
		GetLocalTime(&sys);
		CString PREMIUM;	
		calDeviation();
		deviationHigh_save = deviationHigh;
		deviationLow_save = deviationLow;
		PREMIUM.Format(_T("%.4f"),premiumLow);	
		clientDlg->SetDlgItemTextA(IDC_EDIT18,PREMIUM);
		PREMIUM.Format(_T("%.4f"),premiumHigh);	
		clientDlg->SetDlgItemTextA(IDC_EDIT16,PREMIUM);
		//非交易日返回
		if(!isTradeDay(sys.wYear,sys.wMonth,sys.wDay))
		{
			continue;
		}
		//非常规交易时间
		if((sys.wHour == 9 && sys.wMinute < 10) || 
			(sys.wHour == 15 && sys.wMinute > 15) ||
			(sys.wHour == 11 && sys.wMinute > 30) ||
			(sys.wHour == 12)||
			(sys.wHour < 9) || (sys.wHour > 15)){
				continue;
		}
		if(clientDlg->tradeEnd){//终止
			//做清空处理,重新启动时会初始化
			return -1;
		}
		if(clientDlg->stop){//暂停
			continue;
		}
		if(_isnan(datumDiff) != 0 || _isnan(premium)!=0 ||_isnan(deviation)!=0){
			continue;//判断非零值错误
		}
		if(deviationHigh >= 100 || deviationLow <= -100){
			continue;//超过范围,返回
		}
		for(int i = 0;i <= NUMLADDER - 1;i++){//计算当前的区间位置
			if(deviationLow >= ladder_01[i] && deviationHigh <= ladder_01[i + 1]){
				if(isFirst){
					nowSection = i;
					isFirst = false;
					break;
				}
				else{
					if(nowSection != i){
						nowSection = i;
						break;
					}
				}
			}
		}
		if(nowSection == 4444){
			continue;//还未找到区间,返回重新寻找
		}
		bool isFilledL = false,isFilledR = false;
		int needA50L = 0,needA50R = 0;
		int needIfL = 0,needIfR = 0;
		needIfL = -needAmount_01[nowSection];
		needIfR = -needAmount_01[nowSection + 1];
		needA50L = needAmount_01[nowSection] * multiply;
		needA50R = needAmount_01[nowSection + 1] * multiply;
		//强平
		if(holdA50_01 > needA50L){
			//FTA50(holdA50_01 - needA50L,false);
			holdA50_01 = needA50L;
		}
		if(holdIf_01 < needIfL){
			//FTIF(needIfL - holdIf_01,true);
			holdIf_01 = needIfL;
		}
		if(holdA50_01 < needA50R){
			//FTA50(needA50R - holdA50_01,true);
			holdA50_01 = needA50R;
		}
		if(holdIf_01 > needIfR){
			//FTIF(holdIf_01 - needIfR,false);
			holdIf_01 = needIfR;
		}
		//查询a50账户可用资金
		//

		if(nowSection < (NUMLADDER - 1) / 2){
			if(holdA50_01 < needA50L || holdIf_01 < needIfL){
				isFilledL = false;
			}
			if(holdA50_01 < needA50R || holdIf_01 < needIfR){
				isFilledR = false;
			} 
		}

		/*
		if(deviation <= (ladder_01[nowSection] + ladder_01[nowSection + 1]) / 2.0){
		double A50Price = ladder_01[nowSection] + datumDiff + ifBid1 * A50Index / HS300Index + A50Index * dltInterest;
		buyOrSell_01(holdA50_01,holdIf_01,needAmount_01[nowSection] * multiply,true);
		}
		else{
		double A50Price = ladder_01[nowSection + 1] + datumDiff + ifAsk1 * A50Index / HS300Index + A50Index * dltInterest;
		buyOrSell_01(holdA50_01,holdIf_01,needAmount_01[nowSection + 1] * multiply,false);
		}
		*/
	}
	return 0;
}
Esempio n. 2
0
void MCThreadCleanupFn()
{
	g_MCThreadExitEvent.SetEvent();
}
Esempio n. 3
0
void CQEventWidget1::addEvent(UndoEventData *pSData)
{
  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  CModel * pModel = pDataModel->getModel();
  assert(pModel != NULL);

  //reinsert the Event
  CEvent *pEvent =  pModel->createEvent(pSData->getName());

  //set the expressions
  pEvent->setTriggerExpression(pSData->getTriggerExpression());
  pEvent->setDelayExpression(pSData->getDelayExpression());
  pEvent->setPriorityExpression(pSData->getPriorityExpression());

  QList <UndoEventAssignmentData *> *assignmentData = pSData->getEventAssignmentData();
  QList <UndoEventAssignmentData *>::const_iterator i;

  for (i = assignmentData->begin(); i != assignmentData->end(); ++i)
    {
      UndoEventAssignmentData * assignData = *i;

      CCopasiObject * pObject = NULL;
      bool speciesExist = false;
      size_t ci;

      for (ci = 0; ci < pModel->getCompartments().size(); ci++)
        {
          CCompartment * pCompartment = pModel->getCompartments()[ci];

          if (pCompartment->getMetabolites().getIndex(assignData->getName()) != C_INVALID_INDEX)
            speciesExist = true;
        }

      if (speciesExist)
        {
          size_t index = pModel->findMetabByName(assignData->getName());
          pObject =  pModel->getMetabolites()[index];
        }
      else if (pModel->getModelValues().getIndex(assignData->getName()) != C_INVALID_INDEX)
        {
          pObject = pModel->getModelValues()[assignData->getName()];
        }
      else if (pModel->getReactions().getIndex(assignData->getName()) != C_INVALID_INDEX)
        {
          pObject = pModel->getReactions()[assignData->getName()];
        }

      const CModelEntity * pEntity = dynamic_cast< const CModelEntity * >(pObject);
      CEventAssignment *eventAssign = new CEventAssignment(pObject->getKey(), pEvent->getObjectParent());
      eventAssign->setExpression(assignData->getExpression());
      eventAssign->getExpressionPtr()->compile();
      pEvent->getAssignments().add(eventAssign);
    }

  std::string key = pEvent->getKey();
  protectedNotify(ListViews::EVENT, ListViews::ADD, key);

  mpListView->switchToOtherWidget(C_INVALID_INDEX, key);
}
Esempio n. 4
0
//以下为Delphi传入数据包
extern "C" _declspec(dllexport) int __stdcall Send(int flag,void * Pin)

{

	try
	{


		if (flag==1||flag==2||flag==3)
		{

		
		if (g_LCStatusFlag<=1 )
		{	
			
			return MMLCConnect(flag,Pin);
			

		}
		else
		{
			return 30040;
		}

		}




		if (flag==1003)
		{
			if (strlen(((SingleFava*)Pin)->chatTxt)>1000)
			{
				return 30030;
			}

		}

		TRACE("调用Send flag:%d",flag);

		if (GetSockStatus()!=0)
		{
			return GetSockStatus();
		}

		g_objectCComAutoCriticalSection.Lock();
		CDataClass * pCDataClass=new CDataClass(flag,Pin);	
		global_socket->ListInPacket_Push(pCDataClass);
		/*int i=SendPackge(g_socketServer);*/

		g_objectCComAutoCriticalSection.Unlock();
		EventSend.SetEvent();
		//global_socket.AsyncSelect(FD_WRITE);
		return 0;



	}
	catch (CMemoryException* e)
	{
		return 30050;
		
	}
	catch (CFileException* e)
	{
		return 30051;
	}
	catch (CException* e)
	{
		return 30052;
	}
	catch(...)
	{
       return 30053;
	}

	// return 0;

	
}
Esempio n. 5
0
int CServerApp::mainLoop()
{
	// create socket multiplexer.  this must happen after daemonization
	// on unix because threads evaporate across a fork().
	CSocketMultiplexer multiplexer;

	// create the event queue
	CEventQueue eventQueue;

	// if configuration has no screens then add this system
	// as the default
	if (args().m_config->begin() == args().m_config->end()) {
		args().m_config->addScreen(args().m_name);
	}

	// set the contact address, if provided, in the config.
	// otherwise, if the config doesn't have an address, use
	// the default.
	if (args().m_synergyAddress->isValid()) {
		args().m_config->setSynergyAddress(*args().m_synergyAddress);
	}
	else if (!args().m_config->getSynergyAddress().isValid()) {
		args().m_config->setSynergyAddress(CNetworkAddress(kDefaultPort));
	}

	// canonicalize the primary screen name
	CString primaryName = args().m_config->getCanonicalName(args().m_name);
	if (primaryName.empty()) {
		LOG((CLOG_CRIT "unknown screen name `%s'", args().m_name.c_str()));
		return kExitFailed;
	}

	// start server, etc
	ARCH->util().startNode();

	// handle hangup signal by reloading the server's configuration
	ARCH->setSignalHandler(CArch::kHANGUP, &reloadSignalHandler, NULL);
	EVENTQUEUE->adoptHandler(getReloadConfigEvent(),
		IEventQueue::getSystemTarget(),
		new TMethodEventJob<CServerApp>(this, &CServerApp::reloadConfig));

	// handle force reconnect event by disconnecting clients.  they'll
	// reconnect automatically.
	EVENTQUEUE->adoptHandler(getForceReconnectEvent(),
		IEventQueue::getSystemTarget(),
		new TMethodEventJob<CServerApp>(this, &CServerApp::forceReconnect));

	// to work around the sticky meta keys problem, we'll give users
	// the option to reset the state of synergys
	EVENTQUEUE->adoptHandler(getResetServerEvent(),
		IEventQueue::getSystemTarget(),
		new TMethodEventJob<CServerApp>(this, &CServerApp::resetServer));

	// run event loop.  if startServer() failed we're supposed to retry
	// later.  the timer installed by startServer() will take care of
	// that.
	CEvent event;
	DAEMON_RUNNING(true);
	EVENTQUEUE->getEvent(event);
	while (event.getType() != CEvent::kQuit) {
		EVENTQUEUE->dispatchEvent(event);
		CEvent::deleteData(event);
		EVENTQUEUE->getEvent(event);
	}
	DAEMON_RUNNING(false);

	// close down
	LOG((CLOG_DEBUG1 "stopping server"));
	EVENTQUEUE->removeHandler(getForceReconnectEvent(),
		IEventQueue::getSystemTarget());
	EVENTQUEUE->removeHandler(getReloadConfigEvent(),
		IEventQueue::getSystemTarget());
	cleanupServer();
	updateStatus();
	LOG((CLOG_NOTE "stopped server"));

	return kExitSuccess;
}
Esempio n. 6
0
int Receive(SOCKET s)
{
	////////////////////////////////////
	//static int i=0;

	TRACE("获得一个OnReceive事件");
	//i++;
	/*BYTE * pRightEndTemp;*/

	BYTE buff[65536];
	memset(buff,0x00,65536);
	int nRead;
	nRead = recv(s,(char*)buff, 65536,0); 
	TRACE("已经接收数据 长度%d",nRead);
	switch (nRead)
	{
	case 0:
		//SetSockClose();
		//closesocket(g_socketServer);
		//UnInitSock();   

		TRACE("开始关闭连接");
		//shutdown(g_socketServer,SD_SEND);
		/*EventExit.SetEvent();*/
		THROW(1);

		return WSAGetLastError();
		//case -1:
		//	Close();
		//	break;
	case SOCKET_ERROR:
		if (GetLastError() != WSAEWOULDBLOCK) 
		{
			TRACE("收到WSAEWOULDBLOCK");
			//AfxMessageBox ("Error occurred");
			//SetSockClose();
			//UnInitSock();  
			//shutdown(g_socketServer,SD_SEND);
			/*EventExit.SetEvent();*/
			THROW(1);
			return WSAGetLastError();
		}
		else
		{
			return WSAEWOULDBLOCK;
		}

	default://接收到了数据
		TRACE("接收到了数据");

		if (global_socket->pDataEnd==&(global_socket->pRecvOriginal[0]))//缓冲区为空
		{

			memcpy(global_socket->pDataEnd,buff,nRead);
			global_socket->pDataEnd=global_socket->pDataEnd+nRead-1;
		}
		else
		{//缓冲区有数据
			memcpy(global_socket->pDataEnd+1,buff,nRead);
			global_socket->pDataEnd=global_socket->pDataEnd+1+nRead-1;//    +nRead-1;


		}

	    while(global_socket->pDataEnd-&(global_socket->pRecvOriginal[0]) > 21)
	    
		
	  {
			BYTE * pRightEndTemp;
		
		int i=global_socket->CheckWheaverHaveRightData(&pRightEndTemp);


		TRACE("调用CheckWheaverHaveRightData %d",i);
		if (i==1)//正确包

		{
			TRACE("正确数据包");

			DataReved * pDataReved=new DataReved(global_socket->pHead,pRightEndTemp);
			TRACE("组装接收对象 %d",pDataReved->routeType);
			if (pDataReved->routeType==0||pDataReved->routeType==1)//flex
			{

				/*LC_NSend("LCFlexClient","LCFlexRecvFromNetWork",4,pDataReved->byteDataRecvOrigianl,pDataReved->lengthofbyteDataRecvOrigianl);*/
				
				if (g_LCStatusFlag<=1 )
				{
					LC_NSend("_airToWeb","airToWebHandler",4,pDataReved->byteDataRecvOrigianl,pDataReved->lengthofbyteDataRecvOrigianl);
				}
				//to lC control
			}
			if (pDataReved->routeType==0||pDataReved->routeType==1)//flex
			{
				TRACE("to mm flag %d",pDataReved->flag);
				if (pDataReved->flag==1000)
				{
					TRACE("设置EventConnectFava");
					//::SetEvent(hEvent);
					if (strcmp("yes",((ConnectFava*)pDataReved->p_ToDelphiData)->status)==0)
					{ iError=0;
					TRACE("yes");

					Sleep(500);
					EventConnectFava.SetEvent();

					}
					else
					{
						TRACE("no");
						iError=30011;
						Sleep(500);

						EventConnectFava.SetEvent();

					}

				}
				if (pDataReved->flag==1012)
				{

					TRACE("设置EventConnectFava");
					//::SetEvent(hEvent);
					if (((PlayerFava*)pDataReved->p_ToDelphiData)->playerStatus==0||((PlayerFava*)pDataReved->p_ToDelphiData)->playerStatus==1)
					{ 
						//iError=((PlayerFava*)pDataReved->p_ToDelphiData)->playerStatus;
						iError=0;
						TRACE("yes");

						Sleep(500);
						EventPlayerFava1012.SetEvent();

					}
					else
					{
						TRACE("no");
						iError=30012;
						Sleep(500);

						EventPlayerFava1012.SetEvent();

					}
					//EventPlayerFava1012.SetEvent();

				}
				if (pDataReved->flag==1013)
				{

					TRACE("设置EventConnectFava");
					//::SetEvent(hEvent);
					if (((PlayerFava*)pDataReved->p_ToDelphiData)->playerSkill==0)
					{ 
						iError=((PlayerFava*)pDataReved->p_ToDelphiData)->playerSkill;
						TRACE("yes");

						Sleep(500);
						EventPlayerFava1013.SetEvent();

					}
					else
					{
						TRACE("no");
						iError=30013;
						Sleep(500);

						EventPlayerFava1013.SetEvent();

					}
					//EventPlayerFava1013.SetEvent();

				}
				if (pDataReved->flag==1014)
				{
					EventPlayerFava1014.SetEvent();

				}
				if ((pDataReved->flag!=1000)&&(pDataReved->flag!=1012)&&(pDataReved->flag!=1013)&&(pDataReved->flag!=1014))
				{//回调函数

					    TRACE("调用回调函数,%d",pDataReved->flag);
						TRACE("调用SetDataCallBack,%d",DataCallBackFunc);
						TRACE(",pDataReved->p_ToDelphiData ,%d",pDataReved->p_ToDelphiData);
					(*DataCallBackFunc)(pDataReved->flag,pDataReved->p_ToDelphiData);
					TRACE(",调用完成 pDataReved->p_ToDelphiData ,%d",pDataReved->p_ToDelphiData);


				}


			}
			delete pDataReved;

			TRACE("销毁 pDataReved");
			TRACE("调用ClearOneDataZone");
			global_socket->ClearOneDataZone(pRightEndTemp+1);

		}
		if (i==2)//找到结束符不过偏移量和长度不适合 返回最后结束符,部分清理 
		{
			global_socket->ClearOneDataZone(pRightEndTemp+1);
		}
		if (i==3)//3//超限,错误 全清
		{
			//memset(pRecvOriginal,0x00,65536);
			memset(global_socket->pRecvOriginal,0x00,65536);
			global_socket->pDataEnd=global_socket->pRecvOriginal;
			global_socket->pHead=global_socket->pRecvOriginal;
			global_socket->pRightEnd=global_socket->pRecvOriginal;
		}
		if (i==4)//4;//到有效数据结尾还没有发现结束符,数据保留
		{
           break;
		}
	  }

		
	}
}
Esempio n. 7
0
DWORD WINAPI ServiceThread(LPVOID lpThreadParameter)  
//UINT ServiceThread( LPVOID lpThreadParameter )
//unsigned int WINAPI ServiceThread(void* lpThreadParameter)  
////////////////////////////////////////////////
{   

	::CoInitialize(NULL);
	

	ST_THREAD_PARAM* pThread = (ST_THREAD_PARAM*)lpThreadParameter;   
	SOCKET socketServer = pThread->socket;   
	WSAEVENT wsaEvent = pThread->wsaEvent;   
////////////////////////////
	HANDLE hmultihandle[4];
	hmultihandle[0]=wsaEvent;
	hmultihandle[1]=EventExit.m_hObject;
	hmultihandle[2]=EventSend.m_hObject;
	hmultihandle[3]=EventSendFromFlex.m_hObject;


	TRACE("新线程%d起动/n",GetCurrentThreadId());   

	try
	{

		while(true)   
		{   
			int nRet=::WSAWaitForMultipleEvents(4,hmultihandle,FALSE,10000,FALSE);  
			TRACE("WSAWaitForMultipleEvents %d",nRet);
			if(nRet==WAIT_FAILED) // 失败   
			{   
				 ///////////////////////////////
				TRACE("failed WSAWaitForMultipleEvents/n");   
				THROW(1); 
				break;   
			}   
			else if(nRet==WSA_WAIT_TIMEOUT) // 超时   
			{   
				TRACE(" WSA_WAIT_TIMEOUT ... /n");
				//////////////////////////////////
				/*		int i=0;
				THROW(i);*/
				///////////////////////////////////////////
				continue;   
			}   
			else if (nRet==WSA_WAIT_EVENT_0)

				// 成功 -- 网络事件发生   
			{   
				WSANETWORKEVENTS wsaNetEvent;   
				::WSAEnumNetworkEvents(socketServer,wsaEvent,&wsaNetEvent);   
				TRACE("WSAEnumNetworkEvents",nRet);
				if(wsaNetEvent.lNetworkEvents&FD_READ)   
				{      
					g_objectCComAutoCriticalSection.Lock();
					Receive(g_socketServer);
					g_objectCComAutoCriticalSection.Unlock();
					

				}   
				else if(wsaNetEvent.lNetworkEvents&FD_WRITE)   
				{   

					g_objectCComAutoCriticalSection.Lock();
					SendPackge(g_socketServer);
					g_objectCComAutoCriticalSection.Unlock();
					EventSend.ResetEvent();
					  
				}   
				if(wsaNetEvent.lNetworkEvents&FD_CLOSE)   
				{   
					TRACE("FD_CLOSE event occurs.../n");   
					int nErrorCode = WSAGetLastError();   
					TRACE("Error code is %d/n",nErrorCode);   
					if (nErrorCode == WSAECONNRESET)   
					{   
						TRACE("WSAECONNRESET error./n");   
					}   
					else if (nErrorCode == WSAENETDOWN)   
					{   
						TRACE("WSAENETDOWN error./n");   
					}   
					else if (nErrorCode == WSAENETRESET)   
					{   
						TRACE("WSAENETRESET error./n");   
					}   
					THROW(1);


					



					TRACE("线程%d退出/n",GetCurrentThreadId()); 
					TRACE("线程%d退出/n",GetCurrentThreadId()); 


					return 0; 
					TRACE("无法执行的代码");
				}   
			}  
			else if (nRet==WSA_WAIT_EVENT_0+1)
			{

				THROW(2);
				
				return 0; 
				TRACE("无法执行的代码");
			}

			else if (nRet==WSA_WAIT_EVENT_0+2)
			{
				EventSend.ResetEvent();
				g_objectCComAutoCriticalSection.Lock();
				int i=SendPackge(g_socketServer);
				g_objectCComAutoCriticalSection.Unlock();
				//send 方法
			}
			else if (nRet==WSA_WAIT_EVENT_0+3)
			{
				EventSendFromFlex.ResetEvent();
				g_objectCComAutoCriticalSection.Lock();
				int i=SendPackge(g_socketServer);
				g_objectCComAutoCriticalSection.Unlock();
				//send 方法
			}
		}  



	}
	catch(int& j)
	{


		TRACE("线程%d退出/n",GetCurrentThreadId()); 
		TRACE("线程%d退出/n",GetCurrentThreadId());

		if (j==1)
		{
			(*EventCallBackFunc)(2,0,NULL);
			UnInitSock();
			delete global_socket;
		}
		 
		if (j==2)
		{

			UnInitSock();
			delete global_socket;
			EventExit.ResetEvent();
           EventExitBack.SetEvent();
		}
		return 0;


	}
	catch (CMemoryException* e)
	{
		
	}
	catch (CFileException* e)
	{
	}
	catch (CException* e)
	{
	}
	 



	TRACE("线程1%d退出/n",GetCurrentThreadId());   

	EventExit.SetEvent();
	return 0;   
}  
Esempio n. 8
0
int 
Cam_int_edit::choose(
   CEvent &e,
   State *&s
   )
{
   DEVice_2d *ptr =(DEVice_2d *)e._d;
   PIXEL      te   (ptr->cur());
   XYvec      delta(ptr->delta());
   double     tdelt(the_time() - _dtime);
   
   _dist += sqrt(delta * delta);

   VEXEL sdelt(te - _start_pix);

   int xa=0,ya=1;
   if (Config::get_var_bool("FLIP_CAM_MANIP",false,true))
      swap(xa,ya);
     
   if (fabs(sdelt[ya])/sdelt.length() > 0.9 && tdelt > 0.05) {
      s = &_cam_zoom;
      ptr->set_old(_start_pix);
   } else if (tdelt < 0.1 && _dist < 0.03)
      return 0;
   else {
      if (fabs(sdelt[xa])/sdelt.length() > 0.6 )
         s = &_cam_pan;
      else s = &_cam_zoom;
      ptr->set_old(_start_pix);
   }
   /* if we got this far, we actually have a valid choice, so save the camera */   VIEWptr         view(e.view());
   view->save_cam();

   return 0;
}
int main(int argc, char* argv[])
{
	SpewOutputFunc( MySpewFunc );

	// Figure out a random port to use.
	CCycleCount cnt;
	cnt.Sample();
	CUniformRandomStream randomStream;
	randomStream.SetSeed( cnt.GetMicroseconds() );
	int iPort = randomStream.RandomInt( 20000, 30000 );


	g_ClientPacketEvent.Init( false, false );

	
	// Setup the "server".
	CHandlerCreator_Server serverHandler;
	CIPAddr addr( 127, 0, 0, 1, iPort );

	ITCPConnectSocket *pListener = ThreadedTCP_CreateListener( 
		&serverHandler,
		(unsigned short)iPort );

	
	// Setup the "client".
	CHandlerCreator_Client clientCreator;
	ITCPConnectSocket *pConnector = ThreadedTCP_CreateConnector( 
		CIPAddr( 127, 0, 0, 1, iPort ),
		CIPAddr(),
		&clientCreator );


	// Wait for them to connect.
	while ( !g_pClientSocket )
	{
		if ( !pConnector->Update( &g_pClientSocket ) )
		{
			Error( "Error in client connector!\n" );
		}
	}
	pConnector->Release();


	while ( !g_pServerSocket )
	{
		if ( !pListener->Update( &g_pServerSocket ) )
			Error( "Error in server connector!\n" );
	}
	pListener->Release();


	// Send some data.
	__int64 totalBytes = 0;
	CCycleCount startTime;
	int iPacket = 1;

	startTime.Sample();
	CUtlVector<char> buf;

	while ( (GetAsyncKeyState( VK_SHIFT ) & 0x8000) == 0 )
	{
		int size = randomStream.RandomInt( 1024*0, 1024*320 );
		if ( buf.Count() < size )
			buf.SetSize( size );

		if ( g_pClientSocket->Send( buf.Base(), size ) )
		{
			// Server receives the data and echoes it back. Verify that the data is good.
			WaitForSingleObject( g_ClientPacketEvent.GetEventHandle(), INFINITE );
			Assert( memcmp( g_ClientPacket.Base(), buf.Base(), size ) == 0 );

			totalBytes += size;
			CCycleCount curTime, elapsed;
			curTime.Sample();
			CCycleCount::Sub( curTime, startTime, elapsed );
			double flSeconds = elapsed.GetSeconds();
			Msg( "Packet %d, %d bytes, %dk/sec\n", iPacket++, size, (int)(((totalBytes+511)/1024) / flSeconds) );
		}
	}
	
	g_pClientSocket->Release();
	g_pServerSocket->Release();
	return 0;
}
UINT CProcessPaste::MarkAsPastedThread(LPVOID pParam)
{
	DWORD startTick = GetTickCount();

	static CEvent UpdateTimeEvent(TRUE, TRUE, _T("Ditto_Update_Clip_Time"), NULL);
	UpdateTimeEvent.ResetEvent();

	Log(_T("Start of MarkAsPastedThread"));

	//If running from a U3 device then wait a little before updating the db
	//updating the db can take a second or two and it delays the act of pasting
	if(g_Opt.m_bU3)
	{
		Sleep(350);
	}

	BOOL bRet = FALSE;
	int clipId = 0;

	try
	{
		MarkAsPastedData* pData = (MarkAsPastedData*)pParam;
		if(pData)
		{
			clipId = pData->clipId;
			if(g_Opt.m_bUpdateTimeOnPaste)
			{
				try
				{
					if(pData->pastedFromGroup)
					{
						CppSQLite3Query q = theApp.m_db.execQuery(_T("SELECT clipGroupOrder FROM Main ORDER BY clipGroupOrder DESC LIMIT 1"));

						if(q.eof() == false)
						{
							double latestDate = q.getFloatField(_T("clipGroupOrder"));
							latestDate += 1;

							Log(StrF(_T("Setting clipId: %d, GroupOrder: %f"), pData->clipId, latestDate));

							theApp.m_db.execDMLEx(_T("UPDATE Main SET clipGroupOrder = %f where lID = %d;"), latestDate, pData->clipId);

							theApp.RefreshClipOrder(pData->clipId);
						}
					}
					else
					{
						CppSQLite3Query q = theApp.m_db.execQuery(_T("SELECT clipOrder FROM Main ORDER BY clipOrder DESC LIMIT 1"));

						if(q.eof() == false)
						{
							double latestDate = q.getFloatField(_T("clipOrder"));
							latestDate += 1;

							Log(StrF(_T("Setting clipId: %d, order: %f"), pData->clipId, latestDate));

							theApp.m_db.execDMLEx(_T("UPDATE Main SET clipOrder = %f where lID = %d;"), latestDate, pData->clipId);

							theApp.RefreshClipOrder(pData->clipId);
						}
					}
				}
				CATCH_SQLITE_EXCEPTION
			}

			try
			{
				theApp.m_db.execDMLEx(_T("UPDATE Main SET lastPasteDate = %d where lID = %d;"), (int)CTime::GetCurrentTime().GetTime(), pData->clipId);
			}
			CATCH_SQLITE_EXCEPTION

			delete pData;
			bRet = TRUE;
		}
	}
	CATCH_SQLITE_EXCEPTION

	Log(_T("End of MarkAsPastedThread"));

	DWORD endTick = GetTickCount();
	if((endTick-startTick) > 350)
		Log(StrF(_T("Paste Timing MarkAsPastedThread: %d, ClipId: %d"), endTick-startTick, clipId));

	UpdateTimeEvent.SetEvent();
	return bRet;
}
Esempio n. 11
0
int
Cam_int_edit::down2(
   CEvent &e, 
   State *&s
   )
{
   DEVice_buttons *btns = (DEVice_buttons *)e._d;
   DEVice_2d      *ptr  = btns->ptr2d();

   _view = e.view();

   CAMdataptr  data(_view->cam()->data());
   RAYhit      r   (_view->intersect(ptr->cur()));
   if (r.success()) {
      //////////////////
      //Scale Button
      //////////////////
      if(r.geom()->name() == "scale")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_scale)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("scale");
                  s = &_scale;
               }
         }
      //////////////////
      //ScaleX Button
      //////////////////
      if(r.geom()->name() == "scalex")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_scalex)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("scalex");
                  s = &_scalex;
               }
         }
      //////////////////
      //ScaleY Button
      //////////////////
      if(r.geom()->name() == "scaley")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_scaley)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("scaley");
                  s = &_scaley;
               }
         }
      //////////////////
      //ScaleZ Button
      //////////////////
      if(r.geom()->name() == "scalez")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_scalez)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("scalez");
                  s = &_scalez;
               }
         }
      //////////////////
      //Rotate Button
      //////////////////
      if(r.geom()->name() == "rotateX")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_rot_x)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("rotateX");
                  s = &_rot_x;
               }
         }
      //////////////////
      //RotateY Button
      //////////////////
      if(r.geom()->name() == "rotateY")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_rot_y)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("rotateY");
                  s = &_rot_y;
               }
         }
      //////////////////
      //Rotate Button
      //////////////////
      if(r.geom()->name() == "rotateZ")
         {
            BaseJOTapp::deactivate_button();
            if(s == &_rot_z)
               s = (State *)-1;
            else
               {
                  BaseJOTapp::activate_button("rotateZ");
                  s = &_rot_z;
               }
         }
      /////////////////
      //Eye Button
      ////////////////
      else if(r.geom()->name() == "eye_button")
         {
            s = (State *)-1;
            BaseJOTapp::cam_switch(e,s);
         }
   }
   return 0;
}
Esempio n. 12
0
void
CClient::handleFileChunkSending(const CEvent& event, void*)
{
	sendFileChunk(event.getData());
}
Esempio n. 13
0
UINT IfEntry(LPVOID pParam){
	IfInData * data = (IfInData*)pParam;
	CThostFtdcInputOrderField req;
	memset(&req, 0, sizeof(req));
	///经纪公司代码
	strcpy(req.BrokerID, BROKER_ID);
	///投资者代码
	strcpy(req.InvestorID, INVESTOR_ID);
	///合约代码
	strcpy(req.InstrumentID, INSTRUMENT_ID);
	///报单引用
	//strcpy(req.OrderRef, ORDER_REF);
	sprintf(req.OrderRef,"%d",data->orf);
	///用户代码
	//	TThostFtdcUserIDType	UserID;
	///报单价格条件: 限价
	req.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
	///买卖方向: 
	if(data->isbuy){
		req.Direction = THOST_FTDC_D_Buy;
	}
	else{
		req.Direction = THOST_FTDC_D_Sell;
	}
	///组合开平标志: 开仓
	if(!data->isflat){
		req.CombOffsetFlag[0] = THOST_FTDC_OF_Open;
	}
	else{
		req.CombOffsetFlag[0] = THOST_FTDC_OF_Close;
	}
	///组合投机套保标志
	req.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation;
	///价格
	::EnterCriticalSection(&g_IfPrice);
	if(!data->isbuy){
		req.LimitPrice = ifBid1 - 150.0;
#ifdef _debug
		req.LimitPrice = ifAsk1 + 3;
#endif
	}
	else{
		req.LimitPrice = ifAsk1 + 150.0;
#ifdef _debug
		req.LimitPrice = ifBid1 - 3;
#endif
	}
	::LeaveCriticalSection(&g_IfPrice);
	///数量: 1
	req.VolumeTotalOriginal = data->numif;
	///有效期类型: 当日有效
	req.TimeCondition = THOST_FTDC_TC_GFD;
	///GTD日期
	//	TThostFtdcDateType	GTDDate;
	///成交量类型: 任何数量
	req.VolumeCondition = THOST_FTDC_VC_AV;
	///最小成交量: 1
	req.MinVolume = 1;
	///触发条件: 立即
	req.ContingentCondition = THOST_FTDC_CC_Immediately;
	///止损价
	//	TThostFtdcPriceType	StopPrice;
	///强平原因: 非强平
	req.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
	///自动挂起标志: 否
	req.IsAutoSuspend = 0;
	///业务单元
	//	TThostFtdcBusinessUnitType	BusinessUnit;
	///请求编号
	//	TThostFtdcRequestIDType	RequestID;
	///用户强评标志: 否
	req.UserForceClose = 0;

	std::vector<CThostFtdcOrderField> orderRes;
	std::map<CString,std::vector<CThostFtdcOrderField>>::iterator iOrderRtn;
	std::map<CString,std::vector<CThostFtdcTradeField>>::iterator iTradeRtn;
	std::vector<CThostFtdcOrderField>::iterator iOrderRtnVec;
	std::vector<CThostFtdcTradeField>::iterator iTradeRtnVec;
	CThostFtdcInputOrderActionField reqNew = {'0','0',0,'0',0,0,0,'0','0','0','0',0,0,'0','0'};//命令动作新的修改
	CThostFtdcOrderField orderOld;
	CString thisSysId;//系统编号,作为已成交合约的识别码
	CString thisRef(req.OrderRef);
	double valueTraded = 0;//成交总价值
	bool isBreakIn = false;//是否因为cancel命令提前终止消息循环
	int volumeTraded = 0;
	int endVolumeThisTrade = 0;
	SYSTEMTIME sys;
	while(true){
		GetLocalTime(&sys);
		if(sys.wHour == 9 && sys.wMinute <= 14){
			//9:15前不下单,等待
			continue;
		}
		else{
			break;
		}
	}
	::EnterCriticalSection(&REQUEST_ID_IF);
	int iResult = pUserApi->ReqOrderInsert(&req, ++iRequestID);
	endVolumeThisTrade = req.VolumeTotalOriginal;
	::LeaveCriticalSection(&REQUEST_ID_IF);
	int lastpos = -1;//命令返回消息队列已经处理的位置
	while(true){ 
		//消息返回处理
		int size = 0;
		SwitchToThread();
		::EnterCriticalSection(&ifDealRtn);
		iOrderRtn = ifOrderRtn.find(thisRef);
		if(iOrderRtn != ifOrderRtn.end() && iOrderRtn->second.size() != 0){//证明里边已经有了消息
			//if(iOrderRtn->second.size() != 0){
			size = iOrderRtn->second.size();
			for(int k = 0/*lastpos + 1*/;k < size;k++){
				iOrderRtnVec = iOrderRtn->second.begin() + k;
				orderOld = *iOrderRtnVec;//获取返回的报单命令,状态会不停变化,取到队列末尾,取最新的命令
				thisSysId = iOrderRtnVec->OrderSysID;//获取报单编号
				TRACE("报单引用=%s,报单编号=%s\r\n",iOrderRtnVec->OrderRef,thisSysId);
				/*
				//不管什么原因,均表示已经traded
				if(iOrderRtnVec->VolumeTraded == iOrderRtnVec->VolumeTotalOriginal){
				TRACE("%s\r\n","已经成交,但是从OrderRtn返回");
				::EnterCriticalSection(&avgPriceOfIf);
				valueTraded = valueTraded + iOrderRtnVec->VolumeTraded * iOrderRtnVec->LimitPrice;
				avgpIf avg(data->numif,valueTraded / data->numif);
				avgPriceIf.push_back(avg);
				::LeaveCriticalSection(&avgPriceOfIf);
				//删除键值
				ifOrderRtn.erase(iOrderRtn);
				TRACE("准备脱离ifDealRtn临界区\r\n");
				::LeaveCriticalSection(&ifDealRtn);
				delete (IfInData*)pParam;
				return 0;
				}
				*/
				//如果取消,重新下单
				if(iOrderRtnVec->OrderStatus == THOST_FTDC_OST_Canceled){
					endVolumeThisTrade = endVolumeThisTrade - (iOrderRtnVec->VolumeTotalOriginal - iOrderRtnVec->VolumeTraded);					
					//删除键值
					//ifOrderRtn.erase(iOrderRtn);
					/*
					isBreakIn = true;
					break;//终止内循环
					*/
				}
			}
			/*
			if(isBreakIn){
			isBreakIn = false;
			lastpos = -1;//重新设置
			::LeaveCriticalSection(&ifDealRtn);
			continue;
			}
			*/
			//lastpos = size - 1;
			//iOrderRtn->second.clear();//清空就可以从0头开始检索
			::LeaveCriticalSection(&ifDealRtn);
			//}
		}
		else{
			//还没生成消息队列,表示指令还未生效,返回继续搜索队列
			::LeaveCriticalSection(&ifDealRtn);
			TRACE("%s\r\n","还没生成消息队列,返回");
			continue;
		}
		//成交返回处理
		::EnterCriticalSection(&ifDealRtn);
		if(endVolumeThisTrade == 0){
			return 0;
		}
		else{
			iTradeRtn = ifTradeRtn.find(thisSysId);
			//证明已经有成交信息返回
			if(iTradeRtn != ifTradeRtn.end()){
				for(iTradeRtnVec = iTradeRtn->second.begin();iTradeRtnVec != iTradeRtn->second.end();iTradeRtnVec++){
					TRACE("%s报单编号是%s\r\n","成交,从TradeRtn返回,",iTradeRtn->second.begin()->OrderSysID);
					::EnterCriticalSection(&avgPriceOfIf);
					valueTraded = valueTraded + iTradeRtnVec->Price * iTradeRtnVec->Volume;
					volumeTraded = volumeTraded + iTradeRtnVec->Volume;
					if(volumeTraded == data->numif){//全部成交
						avgpIf avg(volumeTraded,valueTraded / volumeTraded);
						avgPriceIf.push_back(avg);
						::LeaveCriticalSection(&avgPriceOfIf);
						//删除键值
						ifTradeRtn.erase(iTradeRtn);
						ifOrderRtn.erase(iOrderRtn);
						::LeaveCriticalSection(&ifDealRtn);
						return 0;
					}
					::LeaveCriticalSection(&avgPriceOfIf);
				}
				iTradeRtn->second.clear();//将成交数组清空
			}
		}
		::LeaveCriticalSection(&ifDealRtn);
		if(volumeTraded == endVolumeThisTrade && endVolumeThisTrade < data->numif){//本次成交结束,但是还没有全部成交,需要重新下单
			TRACE("%s\r\n","重新下单");
			::EnterCriticalSection(&g_IfPrice);
			if(req.Direction == THOST_FTDC_D_Buy){//BUY
				req.LimitPrice = ifBid1;
#ifdef _debug
				req.LimitPrice = ifBid1;
#endif
			}
			else{//SELL
				req.LimitPrice = ifAsk1;
#ifdef _debug
				req.LimitPrice = ifAsk1;
#endif
			}
			::LeaveCriticalSection(&g_IfPrice);
			req.VolumeTotalOriginal = data->numif - endVolumeThisTrade;
			endVolumeThisTrade = data->numif;//重新设置
			::EnterCriticalSection(&ODREF);
			iNextOrderRef++;
			TThostFtdcOrderRefType orderRefNew;
			sprintf(orderRefNew,"%d", iNextOrderRef);
			::LeaveCriticalSection(&ODREF);
			strcpy(req.OrderRef,orderRefNew);
			thisRef = CString(orderRefNew);
			::EnterCriticalSection(&REQUEST_ID_IF);
			int iResult = pUserApi->ReqOrderInsert(&req, ++iRequestID);
			::LeaveCriticalSection(&REQUEST_ID_IF);
		}
		//如果价格发生不利变化,取消订单 
		UpdateTrade.Lock(INFINITE);//等待同步事件击发
		::EnterCriticalSection(&g_IfPrice);
		if((req.Direction == THOST_FTDC_D_Buy && req.LimitPrice < ifBid1) ||//买
			(req.Direction == THOST_FTDC_D_Sell && req.LimitPrice > ifAsk1)){//卖
				if (IsTradingOrder(&orderOld)){
					TRACE("%s\r\n","改单动作,删除");
					ReqOrderAction(&orderOld,reqNew);
				}
		}
		::LeaveCriticalSection(&g_IfPrice);
	}
	delete (IfInData*)pParam;
	return iResult;
}
Esempio n. 14
0
int flatOrOpen(int num,bool isbuy,bool isflat){
	if(num <= 0){
		return -1;
	}
	::EnterCriticalSection(&avgPriceOfIf);
	avgPriceIf.clear();//清空统计平均价格的数组
	::LeaveCriticalSection(&avgPriceOfIf);
	int numAvail = 0;//容许开仓数量
	if(!isflat){//表示开仓
		/*
		ReqAccount.ResetEvent();//事件同步,设置为未发信状态
		ReqQryIFTradingAccount();//查询if帐户可用资金
		ReqAccount.Lock(INFINITE);//等待
		if(rtnAvailIfID == rqIfID){
		//留有10和100人民币的余地
		marginIf = ifAsk1 * 300.0 * 0.12;//12%的保证金率
		if(multiply != 0){
		numAvail = min((int)((availA50  - 10.0) / (marginA50 * multiply)),(int)((availIf - 100.0) / marginIf));
		}
		else{
		numAvail = num;
		}
		}
		if(numAvail <= 0){
		return -1;
		}
		num = min(num,numAvail);
		*/
	}
	if(isflat){
		if(isbuy){
			TRACE("买平%d手\r\n",num);
		}
		else{
			TRACE("卖平%d手\r\n",num);
		}
	}
	else{
		if(isbuy){
			TRACE("买开%d手\r\n",num);
		}
		else{
			TRACE("卖开%d手\r\n",num);
		}
	}
	int numofA50 = num * multiply;
	int numofIf = num;
	std::vector<HANDLE> handleThread;//存放线程句柄的数组
	IfInData *data;
	if(isbuy && isflat){
		data = new IfInData(1,false,true,0); 
	}
	else if(isbuy && !isflat)
	{
		data = new IfInData(1,false,false,0);
	}
	else if(!isbuy && isflat){
		data = new IfInData(1,true,true,0);
	}
	else{
		data = new IfInData(1,true,false,0);
	}
	if(numofA50 != 0){
#define PUT(prop,value) orderA50.get()->##prop## = (##value##);
#define GET(prop) orderA50.get()->##prop
		std::auto_ptr<Order> orderA50(new Order());
		double valueTradeA50 = 0;
		::EnterCriticalSection(&g_A50Price);
		if(isbuy){
			PUT(action,"BUY");
			PUT(totalQuantity,numofA50);
#ifdef _case1
			PUT(lmtPrice,a50Ask1 + 100.0);
#else
			PUT(lmtPrice,a50Bid1);
#endif
			PUT(orderType,"LMT");
		}
		else{
			PUT(action,"SELL");
			PUT(totalQuantity,numofA50);
#ifdef _case1
			PUT(lmtPrice,a50Bid1 - 100.0);
#else
			PUT(lmtPrice,a50Ask1);
#endif
			PUT(orderType,"LMT");
		}
		::LeaveCriticalSection(&g_A50Price);
		bool isA50Validate = false;
		int iftraded = 0;//已经发出的if指令,A50每次交易满一手对冲,瞬间发出if指令
		int filledLast = 0;//最近一次的成交数量
		long idThisTrade;//交易id
		std::vector<rtn> rtnres;//交易结果返回
		int lastpos = -1;//上次检查返回新的vector的数据位置,从-1开始,考虑到0位置前用-1表示
		::EnterCriticalSection(&tdi_a50);
		idThisTrade = clientDlg->PlaceOrder_hedge(false,orderA50);
		clientDlg->m_idrtn.insert(std::pair<long,std::vector<rtn>>(idThisTrade,rtnres));
		::LeaveCriticalSection(&tdi_a50);
		while(true){	
			std::map<long,std::vector<rtn>>::iterator iter;
			std::vector<rtn>::iterator ivec;
			int seconds = 0;//计时
			while(!isA50Validate){
				//设置临界区,防止处理期间的m_idrtn变动
				//每次都要重新获取开始位置,因为map中元素次序会变
				::EnterCriticalSection(&tdi_a50);
				iter = clientDlg->m_idrtn.find(idThisTrade);
				if(iter != clientDlg->m_idrtn.end()){
					ivec = iter->second.begin();
					int size = iter->second.size();
					if(size > 0){
						isA50Validate = true;//有返回消息了
						TRACE("A50 HAS VALIDATED\r\n");
						::LeaveCriticalSection(&tdi_a50);
						break;
					}
				}
				TRACE("A50 NOT VALIDATED\r\n");
				::LeaveCriticalSection(&tdi_a50);
				::Sleep(50);//50毫秒检测一次
				seconds = seconds + 50;
				if(seconds > 100000){//100秒没反应,认为指令送达失败
					//重新发送指令
					::EnterCriticalSection(&tdi_a50);
					idThisTrade = clientDlg->PlaceOrder_hedge(false,orderA50);
					clientDlg->m_idrtn.insert(std::pair<long,std::vector<rtn>>(idThisTrade,rtnres));
					::LeaveCriticalSection(&tdi_a50);
					seconds = 0;//重新计时
				}
			}
			::EnterCriticalSection(&tdi_a50);
			iter = clientDlg->m_idrtn.find(idThisTrade);
			if(iter != clientDlg->m_idrtn.end()){
				ivec = iter->second.begin();
				int size = iter->second.size();
				if(size - 1 > lastpos){
					for(int k = lastpos + 1;k < size;k++){
						if((ivec + k)->status == "Submitted" || 
							(ivec + k)->status == "Filled" || 
							(ivec + k)->status == "ApiCancelled" ||
							(ivec + k)->status == "Cancelled"){
								if((ivec + k)->filled > filledLast){
									int needTradeIf = ((ivec + k)->filled - iftraded * multiply) / multiply;//计算需要新交易的if合约数
									if(needTradeIf >= 1){
										//交易if,生成新的线程
										TRACE("begin%d\r\n",needTradeIf);
										data->numif = needTradeIf;
										::EnterCriticalSection(&ODREF);
										iNextOrderRef++;
										data->orf = iNextOrderRef;
										::LeaveCriticalSection(&ODREF);
										IfInData *indata = new IfInData;
										*indata = *data;
										CWinThread *tradeThread = AfxBeginThread(IfEntry,indata,THREAD_PRIORITY_NORMAL,0,0,NULL);
										handleThread.push_back(tradeThread->m_hThread);
										//更新数据
										iftraded = iftraded + needTradeIf;
									}
									//更新上一次已经成交的数目
									filledLast = (ivec + k)->filled;
								}
								if((ivec + k)->status == "Filled" ||
									(ivec + k)->status == "ApiCancelled" ||
									(ivec + k)->status == "Cancelled"){
										//等待if交易线程结束,进行交易平均成本统计
										//等待所有的IF线程交易完毕,返回
										int nCount = handleThread.size();
										if(nCount >= 1){
											HANDLE * handle = new HANDLE[nCount];
											for(int i = 0 ; i < nCount;i++){
												handle[i] = handleThread[i];
											}
											int nIndex = 0;
											DWORD dwRet = 0;
											dwRet = WaitForMultipleObjects(nCount,handle,true,INFINITE);
											switch(dwRet){
											case WAIT_TIMEOUT:
												TRACE("等待超时,退出检测,因为没有被触发的对象了\r\n");
												break;
											case WAIT_FAILED:
												TRACE("等待失败\r\n");
												break;
											default:
												TRACE("已经全部返回\r\n");
												break;
											}
											delete []handle;
										}
										//统计交易成本,开仓则增加交易成本记录,并返回
										::EnterCriticalSection(&avgPriceOfIf);
										double avgIf = 0;
										std::vector<avgpIf>::iterator iavg;
										double totalvalue = 0;
										int totalnum = 0;
										for(iavg = avgPriceIf.begin();iavg != avgPriceIf.end();iavg++){
											totalvalue = totalvalue + iavg->num * iavg->avgprice;
											totalnum = totalnum + iavg->num;
										}
										::LeaveCriticalSection(&avgPriceOfIf);
										if(totalnum>=1){
											avgIf = totalvalue / totalnum;
											::EnterCriticalSection(&g_index);
											double premium_temp = (ivec + k)->avgFillPrice - avgIf * A50Index / HS300Index
												- A50Index * (lifeOfA50 - clientDlg->lifeOfIf) / 365.0 * 0.0631;//6.31%的无风险套利; 
											::LeaveCriticalSection(&g_index);
											double deviation_temp = premium_temp - datumDiff;
#ifdef _weixin
											CString Price_temp("");
											if(!isflat && isbuy){
												Price_temp.Format("BK:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,(ivec + k)->avgFillPrice);
											}
											else if(!isflat && !isbuy){
												Price_temp.Format("SK:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,(ivec + k)->avgFillPrice);
											}
											else if(isflat && isbuy){
												Price_temp.Format("BP:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,(ivec + k)->avgFillPrice);
											}
											else{
												Price_temp.Format("SP:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,(ivec + k)->avgFillPrice);
											}
											clientDlg->SendMsg(Price_temp);
#endif
											if(!isflat){
												HoldAndDirec hd;
												hd.price = deviation_temp;
												if(!isbuy){
													netHold = netHold - totalnum;
													hd.numDirec = -totalnum;
												}
												else{
													netHold = netHold + totalnum;
													hd.numDirec = totalnum;
												}	
												holdHedge.push_back(hd);
											}
										}
										//删除这次交易ID对应的键值
										clientDlg->m_idrtn.erase(iter);
										TRACE("对冲结束,准备脱离临界区\r\n");
										::LeaveCriticalSection(&tdi_a50);
										delete data;
										TRACE("对冲结束,返回0值\r\n");
										return 0;
								}
						}			
						else{
							//NOTHING TO DO
						}
					}
					lastpos = size -1;
				}
			}
			::LeaveCriticalSection(&tdi_a50);
			UpdateTrade.Lock(INFINITE);//等待同步事件击发
			//判断价格是否合理,否则修改A50合约
			calDeviation();//重新计算偏差 
			::EnterCriticalSection(&g_A50Price);
			if(isbuy){
				if(deviationHigh <= deviationHigh_save - 5.0){
					PUT(lmtPrice,a50Ask1);
					clientDlg->ModifyOrder_hedge(idThisTrade,orderA50);
				}
				else if(GET(lmtPrice) < a50Bid1){
					PUT(lmtPrice,a50Bid1);
					clientDlg->ModifyOrder_hedge(idThisTrade,orderA50);
				}
			}
			else{
				if(deviationLow >= deviationLow_save + 5.0){
					PUT(lmtPrice,a50Bid1);
					clientDlg->ModifyOrder_hedge(idThisTrade,orderA50);
				}
				else if(GET(lmtPrice) > a50Ask1){
					PUT(lmtPrice,a50Ask1);	
					clientDlg->ModifyOrder_hedge(idThisTrade,orderA50);
				}
			}
			::LeaveCriticalSection(&g_A50Price);
		}
		delete data;
		return 0;
#undef PUT
#undef GET
	}
	else{
		int needTradeIf = numofIf;
		if(needTradeIf >= 1){
			//交易if,生成新的线程
			TRACE("begin%d\r\n",needTradeIf);
			data->numif = needTradeIf;
			::EnterCriticalSection(&ODREF);
			iNextOrderRef++;
			data->orf = iNextOrderRef;
			::LeaveCriticalSection(&ODREF);
			IfInData *indata = new IfInData;
			*indata = *data;
			CWinThread *tradeThread = AfxBeginThread(IfEntry,indata,THREAD_PRIORITY_NORMAL,0,0,NULL);
			handleThread.push_back(tradeThread->m_hThread);
		}
		int nCount = handleThread.size();
		if(nCount >= 1){
			HANDLE * handle = new HANDLE[nCount];
			for(int i = 0 ; i < nCount;i++){
				handle[i] = handleThread[i];
			}
			int nIndex = 0;
			DWORD dwRet = 0;
			dwRet = WaitForMultipleObjects(nCount,handle,true,INFINITE);
			switch(dwRet){
			case WAIT_TIMEOUT:
				TRACE("等待超时,退出检测,因为没有被触发的对象了\r\n");
				break;
			case WAIT_FAILED:
				TRACE("等待失败\r\n");
				break;
			default:
				TRACE("已经全部返回\r\n");
				break;
			}
			delete []handle;
		}
		//统计交易成本,开仓则增加交易成本记录,并返回
		::EnterCriticalSection(&avgPriceOfIf);
		double avgIf = 0;
		std::vector<avgpIf>::iterator iavg;
		double totalvalue = 0;
		int totalnum = 0;
		double avgFillPriceA50 = 0;
		if(isbuy){
			avgFillPriceA50 = a50Ask1;
		}
		else{
			avgFillPriceA50 = a50Bid1;
		}
		for(iavg = avgPriceIf.begin();iavg != avgPriceIf.end();iavg++){
			totalvalue = totalvalue + iavg->num * iavg->avgprice;
			totalnum = totalnum + iavg->num;
		}
		::LeaveCriticalSection(&avgPriceOfIf);
		if(totalnum>=1){
			avgIf = totalvalue / totalnum;
			::EnterCriticalSection(&g_index);
			double premium_temp = avgFillPriceA50 - avgIf * A50Index / HS300Index
				- A50Index * (lifeOfA50 - clientDlg->lifeOfIf) / 365.0 * 0.0631;//6.31%的无风险套利; 
			::LeaveCriticalSection(&g_index);
			double deviation_temp = premium_temp - datumDiff;
#ifdef _weixin
			CString Price_temp("");
			if(!isflat && isbuy){
				Price_temp.Format("BK:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,avgFillPriceA50);
			}
			else if(!isflat && !isbuy){
				Price_temp.Format("SK:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,avgFillPriceA50);
			}
			else if(isflat && isbuy){
				Price_temp.Format("BP:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,avgFillPriceA50);
			}
			else{
				Price_temp.Format("SP:%d,CB:%f,HS300:%f,IF:%f,A50:%f,XINA50:%f\r\n",totalnum,deviation_temp,HS300Index,avgIf,A50Index,avgFillPriceA50);
			}
			clientDlg->SendMsg(Price_temp);
#endif
			if(!isflat){
				HoldAndDirec hd;
				hd.price = deviation_temp;
				if(!isbuy){
					netHold = netHold - totalnum;
					hd.numDirec = -totalnum;
				}
				else{
					netHold = netHold + totalnum;
					hd.numDirec = totalnum;
				}	
				holdHedge.push_back(hd);
			}
		}
		TRACE("对冲结束,准备脱离临界区\r\n");
		::LeaveCriticalSection(&tdi_a50);
		delete data;
		TRACE("对冲结束,返回0值\r\n");
		return 0;
	}
}
Esempio n. 15
0
int CecCommand(void *UNUSED(cbParam), const cec_command &command)
{
  g_lastCommand = command.opcode;
  g_responseEvent.Signal();
  return 0;
}
Esempio n. 16
0
void
CDaemonApp::handleIpcMessage(const CEvent& e, void*)
{
	CIpcMessage* m = static_cast<CIpcMessage*>(e.getDataObject());
	switch (m->type()) {
		case kIpcCommand: {
			CIpcCommandMessage* cm = static_cast<CIpcCommandMessage*>(m);
			CString command = cm->command();

			// if empty quotes, clear.
			if (command == "\"\"") {
				command.clear();
			}

			if (!command.empty()) {
				LOG((CLOG_DEBUG "new command, elevate=%d command=%s", cm->elevate(), command.c_str()));

				CString debugArg("--debug");
				UInt32 debugArgPos = static_cast<UInt32>(command.find(debugArg));
				if (debugArgPos != CString::npos) {
					UInt32 from = debugArgPos + static_cast<UInt32>(debugArg.size()) + 1;
					UInt32 nextSpace = static_cast<UInt32>(command.find(" ", from));
					CString logLevel(command.substr(from, nextSpace - from));
				
					try {
						// change log level based on that in the command string
						// and change to that log level now.
						ARCH->setting("LogLevel", logLevel);
						CLOG->setFilter(logLevel.c_str());
					}
					catch (XArch& e) {
						LOG((CLOG_ERR "failed to save LogLevel setting, %s", e.what().c_str()));
					}
				}
			}
			else {
				LOG((CLOG_DEBUG "empty command, elevate=%d", cm->elevate()));
			}

			try {
				// store command in system settings. this is used when the daemon
				// next starts.
				ARCH->setting("Command", command);

				// TODO: it would be nice to store bools/ints...
				ARCH->setting("Elevate", CString(cm->elevate() ? "1" : "0"));
			}
			catch (XArch& e) {
				LOG((CLOG_ERR "failed to save settings, %s", e.what().c_str()));
			}

#if SYSAPI_WIN32
			// tell the relauncher about the new command. this causes the
			// relauncher to stop the existing command and start the new
			// command.
			m_watchdog->setCommand(command, cm->elevate());
#endif
			break;
		}

		case kIpcHello:
			CIpcHelloMessage* hm = static_cast<CIpcHelloMessage*>(m);
			CString type;
			switch (hm->clientType()) {
				case kIpcClientGui: type = "gui"; break;
				case kIpcClientNode: type = "node"; break;
				default: type = "unknown"; break;
			}

			LOG((CLOG_DEBUG "ipc hello, type=%s", type.c_str()));

#if SYSAPI_WIN32
			CString watchdogStatus = m_watchdog->isProcessActive() ? "ok" : "error";
			LOG((CLOG_INFO "watchdog status: %s", watchdogStatus.c_str()));
#endif

			m_ipcLogOutputter->notifyBuffer();
			break;
	}
}
Esempio n. 17
0
bool CQRDFTreeView::enterProtected()
{
  clear();

  CCopasiObject *pObject = dynamic_cast< CCopasiObject * >(CCopasiRootContainer::getKeyFactory()->get(mKey));

  if (pObject != NULL)
    {
      CModelEntity * pEntity = NULL;
      CEvent * pEvent = NULL;
      CReaction * pReaction = NULL;
      CFunction * pFunction = NULL;
      const std::string * pMiriamAnnotation = NULL;

      if ((pEntity = dynamic_cast< CModelEntity * >(pObject)) != NULL)
        pMiriamAnnotation = &pEntity->getMiriamAnnotation();
      else if ((pEvent = dynamic_cast< CEvent * >(pObject)) != NULL)
        pMiriamAnnotation = &pEvent->getMiriamAnnotation();
      else if ((pReaction = dynamic_cast< CReaction * >(pObject)) != NULL)
        pMiriamAnnotation = &pReaction->getMiriamAnnotation();
      else if ((pFunction = dynamic_cast< CFunction * >(pObject)) != NULL)
        pMiriamAnnotation = &pFunction->getMiriamAnnotation();

      if (pMiriamAnnotation && *pMiriamAnnotation != "")
        mpGraph = CRDFParser::graphFromXml(*pMiriamAnnotation);
    }

  CCopasiMessage::clearDeque();

  if (CCopasiMessage::size() != 0)
    {
      QString Message = FROM_UTF8(CCopasiMessage::getAllMessageText());
      CQMessageBox::warning(this, QString("RDF Warning"), Message,
                            QMessageBox::Ok, QMessageBox::Ok);
    }

  if (mpGraph == NULL)
    mpGraph = new CRDFGraph;

  // We make sure that we always have an about node.
  mpGraph->createAboutNode(mKey);

  // We iterate of all triplets
  std::set< CRDFTriplet >::const_iterator it = mpGraph->getTriplets().begin();
  std::set< CRDFTriplet >::const_iterator end = mpGraph->getTriplets().end();

  for (; it != end; ++it)
    {
      CQRDFTreeViewItem * pSubjectItem = find(it->pSubject);

      if (pSubjectItem == NULL)
        {
          pSubjectItem = new CQRDFTreeViewItem(mpTreeWidget, NULL);
          insert(it->pSubject, pSubjectItem);
          // Display the subject information

          const CRDFSubject & Subject = it->pSubject->getSubject();

          switch (Subject.getType())
            {
              case CRDFSubject::RESOURCE:
                pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getResource()));
                break;

              case CRDFSubject::BLANK_NODE:
                pSubjectItem->setText(COL_SUBJECT, FROM_UTF8(Subject.getBlankNodeID()));
                break;
            }
        }

      CQRDFTreeViewItem * pObjectItem = NULL;

      if (it->Predicate.getURI() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject")
        {
          pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL);
          insert(it->pObject, pObjectItem);
        }
      else
        pObjectItem = find(it->pObject);

      if (pObjectItem == NULL)
        {
          pObjectItem = new CQRDFTreeViewItem(pSubjectItem, NULL);
          insert(it->pObject, pObjectItem);
        }
      else
        {
          QTreeWidgetItem * pParent = pObjectItem->parent();

          if (pParent == NULL)
            {
              mpTreeWidget->invisibleRootItem()->removeChild(pObjectItem);
              pSubjectItem->addChild(pObjectItem);
            }
          else
            {
              pParent->removeChild(pObjectItem);
              pSubjectItem->addChild(pObjectItem);
            }
        }

      pObjectItem->setTriplet(*it);
    }

  mpTreeWidget->setFocus();

  return true;
}
Esempio n. 18
0
int CLocalSocket::write(const char * szDataBlock, int nSizeOfBlock)
{
	if (NULL == szDataBlock)
		return FUNCTION_WRONG_PARAMETER;

	if (IsAlreadyConnected())
	{
		HANDLE hDataReadEvent, hDataWrittenEvent;

		s_PacketBuffer * pDataBuffer			= GetWriteDataBuffer();
		CMutex dataAccessMutex					= GetWriteDataAccessMutex();
		CEvent dataReadEvent					= GetWriteDataReadEvent();
		CEvent dataWrittenEvent					= GetWriteDataWrittenEvent();

		int nAmountOfPackets	 = nSizeOfBlock / PACKET_SIZE;
		int nLastUsedPacketBytes = nSizeOfBlock % PACKET_SIZE;

		if (0 != nLastUsedPacketBytes && 0 != nAmountOfPackets)
		{
			nAmountOfPackets++;
		}

		if (0 == nAmountOfPackets)
			nAmountOfPackets++;

		if (!dataAccessMutex.lock())
			return LOCAL_SOCKET_ERROR;
		
		pDataBuffer->nPacketsToBeSent  = nAmountOfPackets;
		pDataBuffer->nBytesToBeSent	= PACKET_SIZE;

		dataAccessMutex.unlock();

		int nAmountOfBytesToBeWritten = PACKET_SIZE;
		int nPacketOffset = 0;

			for (int nCur = 0; nCur < nAmountOfPackets; nCur++)
			{
				dataAccessMutex.lock();

				pDataBuffer->nCurrentNumber = nCur;

				if (nCur == nAmountOfPackets - 1)
				{
					(nLastUsedPacketBytes == 0) ? (nLastUsedPacketBytes = PACKET_SIZE) : (pDataBuffer->nBytesToBeSent = nLastUsedPacketBytes);
					nAmountOfBytesToBeWritten = nLastUsedPacketBytes;
				}

				memcpy(&pDataBuffer->cStorage[0], &szDataBlock[nPacketOffset], nAmountOfBytesToBeWritten);
				nPacketOffset += PACKET_SIZE;
				dataWrittenEvent.fire_signal();
				
				dataAccessMutex.unlock();


				if (!dataReadEvent.get_signal())
					return LOCAL_SOCKET_ERROR;

				if (CheckForDisconnection())
					return LOCAL_SOCKET_ERROR;
			}			

			return (nSizeOfBlock);
	}

	return LOCAL_SOCKET_ERROR;
}
Esempio n. 19
0
extern "C" _declspec(dllexport) int __stdcall SendSync(int flag,void * Pin)

{

	try
	{


		if (flag==1003)
		{
			if (strlen(((SingleFava*)Pin)->chatTxt)>MAXMESSAGELENGTH)
			{
				return 30030;
			}

		}

		if (GetSockStatus()!=0)
		{
			return GetSockStatus();
		}

		TRACE("调用SendSync flag:%d",flag);
		TRACE("调用SendSync flag:%d",flag);


		DWORD iErrorNo;
		DWORD iRetWait;



		g_objectCComAutoCriticalSection.Lock();
		TRACE("开始组织数据\n");
		CDataClass * pCDataClass=new CDataClass(flag,Pin);
		//global_socket->ListInPacket.push(pCDataClass);
		global_socket->ListInPacket_Push(pCDataClass);
		g_objectCComAutoCriticalSection.Unlock();
		EventSend.SetEvent();

		//global_socket.AsyncSelect(FD_WRITE);
		TRACE("数据完全生成");
		TRACE("数据完全生成 开始调用发送");
		//int i=SendPackge(g_socketServer);
		//	g_objectCComAutoCriticalSection.Unlock();
		if (flag==1000)
		{

			TRACE("1000节点 开始等待");
			TRACE("开始等待1000");
			BOOL i=EventConnectFava.ResetEvent();

			int dRet=WaitForSingleObject(EventConnectFava,RECVTIMEOUT);


			TRACE("WaitForSingleObject退出");

			if(dRet == WAIT_TIMEOUT)
			{
				TRACE("WaitForSingleObject超时");
				EventExit.SetEvent();
				return 1460;

			}
			else if(dRet == WAIT_OBJECT_0)
			{
				TRACE("WaitForSingleObject正常退出1000________________ iError: %d",iError);
				TRACE("正常退出1000________________");
				return iError;
			}






		}
		if (flag==1012)
		{

			EventPlayerFava1012.ResetEvent();

			int dRet=WaitForSingleObject(EventPlayerFava1012,RECVTIMEOUT);

			if(dRet == WAIT_TIMEOUT)
			{
				EventExit.SetEvent();
				return 1460;

			}
			else if(dRet == WAIT_OBJECT_0)
			{
				TRACE("正常退出1000________________");
				return iError;
			}



			/////////////////////////////////////////////////////////////


		}

		if (flag==1013)
		{

			EventPlayerFava1013.ResetEvent();

			int dRet=WaitForSingleObject(EventPlayerFava1013,RECVTIMEOUT);

			if(dRet == WAIT_TIMEOUT)
			{
				EventExit.SetEvent();
				return 1460;

			}
			else if(dRet == WAIT_OBJECT_0)
			{
				TRACE("正常退出1000________________");
				return iError;
			}



			/////////////////////////////////////////////////////////////


		}

		if (flag==1014)
		{
			EventPlayerFava1014.ResetEvent();

			int dRet=WaitForSingleObject(EventPlayerFava1014,RECVTIMEOUT);

			if(dRet == WAIT_TIMEOUT)
			{
				EventExit.SetEvent();
				return 1460;

			}
			else if(dRet == WAIT_OBJECT_0)
			{
				TRACE("正常退出1000________________");
				return iError;
			}



			/////////////////////////////////////////////////////////////

		}

		return 0;






	}
	catch (CMemoryException* e)
	{
		return 30050;
	}
	catch (CFileException* e)
	{
		return 30051;
	}
	catch (CException* e)
	{
		return 30052;
	}
	catch(...)
	{
		return 30053;

	}

}
Esempio n. 20
0
int CLocalSocket::read(char * szDataBlock, int nSizeOfBlock)
{
	if (NULL == szDataBlock)
		return FUNCTION_WRONG_PARAMETER;

	if (IsAlreadyConnected())
	{
		HANDLE hDataReadEvent, hDataWrittenEvent;

		s_PacketBuffer * pDataBuffer			= GetReadDataBuffer();
		CMutex dataAccessMutex					= GetReadDataAccessMutex();
		CEvent dataReadEvent					= GetReadDataReadEvent();
		CEvent dataWrittenEvent					= GetReadDataWrittenEvent();

		dataWrittenEvent.SetTimeout(INFINITE);

		if (!dataWrittenEvent.get_signal())
			return LOCAL_SOCKET_ERROR;

		if (CheckForDisconnection())
			return LOCAL_SOCKET_ERROR;

		int nAmountOfIncomingPackets = 0;

		if (!dataAccessMutex.lock())
			return LOCAL_SOCKET_ERROR;

		nAmountOfIncomingPackets = pDataBuffer->nPacketsToBeSent;		

		int nPacketOffset = 0;

		if (nAmountOfIncomingPackets > 1)
		{
			int nLastUsedPacketBytes = 0;
			for(int nCur = 0; nCur < nAmountOfIncomingPackets; nCur++)
			{
				if (nCur > 0)
				{
					if (!dataWrittenEvent.get_signal())
						return LOCAL_SOCKET_ERROR;

					if (CheckForDisconnection())
						return LOCAL_SOCKET_ERROR;

					if (!dataAccessMutex.lock())
						return LOCAL_SOCKET_ERROR;
				}

				if (nCur == nAmountOfIncomingPackets - 1)
					nLastUsedPacketBytes = pDataBuffer->nBytesToBeSent;

				int nAmountOfIncomingBytes = pDataBuffer->nBytesToBeSent;
				if (nAmountOfIncomingBytes > nSizeOfBlock)
					// truncate the data
					memcpy(&szDataBlock[nPacketOffset], &pDataBuffer->cStorage[0], nSizeOfBlock);
				else
					memcpy(&szDataBlock[nPacketOffset], &pDataBuffer->cStorage[0], nAmountOfIncomingBytes);

				nPacketOffset += PACKET_SIZE;

				dataAccessMutex.unlock();

				dataReadEvent.fire_signal();
			}

			return (nLastUsedPacketBytes == 0 ? nAmountOfIncomingPackets * PACKET_SIZE : nAmountOfIncomingPackets * PACKET_SIZE - PACKET_SIZE + nLastUsedPacketBytes);

		}
		else
		{
			int nAmountOfIncomingBytes = pDataBuffer->nBytesToBeSent;
			if (nAmountOfIncomingBytes > nSizeOfBlock)
				// truncate the data
				memcpy(szDataBlock, &pDataBuffer->cStorage[0], nSizeOfBlock);
			else
				memcpy(szDataBlock, &pDataBuffer->cStorage[0], nAmountOfIncomingBytes);

			dataAccessMutex.unlock();

			dataReadEvent.fire_signal();

			return nSizeOfBlock;
		}
	}

	return LOCAL_SOCKET_ERROR;
}
Esempio n. 21
0
extern "C" _declspec(dllexport) int __stdcall SetSockClose()

{

	try
	{



		TRACE("调用SetSockClose1");

		if (GetSockStatus()!=0)
		{
			return 0;
		}




		if (g_socketServer != INVALID_SOCKET)   
		{
			//g_iClosesignal=1;////主动连接

			EventExitBack.ResetEvent();
			EventExit.SetEvent();


			//shutdown(g_socketServer,SD_SEND);
			TRACE("开始等待");
			TRACE("threadid %d",hThread);



			WaitForSingleObject(EventExitBack,THREADQUITTIME);//hThread

			CloseHandle(hThread);
			///////////////////////
			//Sleep(500);

			//_endthreadex((unsigned int)hThread);

			TRACE("等待结束");
			//Sleep(500);
			TRACE("WaitForSingleObject(hThread,INFINITE) return ...\n");   
			TRACE("子线程退出");
			delete pThreadParam;
			return 0;
		}



		return 0;



	}
	catch (CMemoryException* e)
	{
		return 30050;
		
	}
	catch (CFileException* e)
	{
		return 30051;
	}
	catch (CException* e)
	{
		return 30052;
	}
	catch(...)
	{
		return 30053;

	}




}
Esempio n. 22
0
void CVideoSyncGLX::Run(CEvent& stopEvent)
{
  unsigned int  PrevVblankCount;
  unsigned int  VblankCount;
  int           ReturnV;
  bool          IsReset = false;
  int64_t       Now;

  //get the current vblank counter
  m_glXGetVideoSyncSGI(&VblankCount);
  PrevVblankCount = VblankCount;

  while(!stopEvent.Signaled() && !m_displayLost && !m_displayReset)
  {
    //wait for the next vblank
    ReturnV = m_glXWaitVideoSyncSGI(2, (VblankCount + 1) % 2, &VblankCount);
    m_glXGetVideoSyncSGI(&VblankCount); //the vblank count returned by glXWaitVideoSyncSGI is not always correct
    Now = CurrentHostCounter();         //get the timestamp of this vblank

    if(ReturnV)
    {
      CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXWaitVideoSyncSGI returned %i", ReturnV);
      return;
    }

    if (VblankCount > PrevVblankCount)
    {
      UpdateClock((int)(VblankCount - PrevVblankCount), Now, m_refClock);
      IsReset = false;
    }
    else
    {
      CLog::Log(LOGDEBUG, "CVideoReferenceClock: Vblank counter has reset");

      //only try reattaching once
      if (IsReset)
        return;

      //because of a bug in the nvidia driver, glXWaitVideoSyncSGI breaks when the vblank counter resets
      CLog::Log(LOGDEBUG, "CVideoReferenceClock: Detaching glX context");
      ReturnV = glXMakeCurrent(m_Dpy, None, NULL);
      if (ReturnV != True)
      {
        CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXMakeCurrent returned %i", ReturnV);
        return;
      }

      //sleep here so we don't busy spin when this constantly happens, for example when the display went to sleep
      Sleep(1000);

      CLog::Log(LOGDEBUG, "CVideoReferenceClock: Attaching glX context");
      ReturnV = glXMakeCurrent(m_Dpy, m_Window, m_Context);
      if (ReturnV != True)
      {
        CLog::Log(LOGDEBUG, "CVideoReferenceClock: glXMakeCurrent returned %i", ReturnV);
        return;
      }

      m_glXGetVideoSyncSGI(&VblankCount);

      IsReset = true;
    }
    PrevVblankCount = VblankCount;
  }
  m_lostEvent.Set();
  while(!stopEvent.Signaled() && m_displayLost && !m_displayReset)
  {
    Sleep(10);
  }
}
Esempio n. 23
0
void WINAPI ReceiveFromLC( int flag,char *lcName,char *methodName,void *ptrPara1,void *ptrPara2,void *ptrPara3)
{



	try
	{



		TRACE("ReceiveFromLC flag:%d,%s,%s",flag,lcName,methodName );

		if (strcmp(lcName,"_XSM_R3")==0)
		{

			if (DataCallBackFunc==NULL)
			{

				TRACE("DataCallBackFunc,NULL");
			}
			else
			{

				PLCControlFava* pPLCControlFava=new PLCControlFava();

				pPLCControlFava->szFlag=flag;
				pPLCControlFava->szMethodName=methodName;
				pPLCControlFava->szPara1=(char*)ptrPara1;
				pPLCControlFava->szPara2=(char*)ptrPara2;
				pPLCControlFava->szPara3=(char*)ptrPara3;

				TRACE("即将调用XSMtoR3 回调函数");
				g_objectCComAutoCriticalSection.Lock();
				(*DataCallBackFunc)(flag,(void*)pPLCControlFava);
				g_objectCComAutoCriticalSection.Unlock();
				TRACE(" 回调函数返回");

				delete pPLCControlFava;
			}


			return ;
		}

		if (strcmp(lcName,"_webToAir")==0)
		{
			TRACE("发现 _webToAir");

			if (strcmp(methodName,"webToAirHandler")==0)
			{

				TRACE("发现 webToAirHandler");
				TRACE("webToAirHandler");



				if (GetSockStatus()!=0)
				{
					TRACE("发现 不联网");
					return;
				}

				TRACE("发现 联网");
				g_objectCComAutoCriticalSection.Lock();

				CDataClass * pCDataClass=new CDataClass((BYTE*)ptrPara1);


				global_socket->ListInPacket.push(pCDataClass);
				g_objectCComAutoCriticalSection.Unlock();

				EventSendFromFlex.SetEvent();

				/*int i=SendPackge(g_socketServer);*/

				//global_socket.AsyncSelect(FD_WRITE);
				//return i;
				return;


			}




		}

		return;






	}
	catch (CMemoryException* e)
	{
			return;
	}
	catch (CFileException* e)
	{
			return;
	}
	catch (CException* e)
	{
			return;
	}
	catch(...)
	{
			return;

	}


}
std::vector<CEvent *> OrganizerCalendarDatabaseAccess::getEvents(int calId, std::string guid, int &pErrorCode)
{
    std::vector<CEvent*> listEvent;

    OrganizerGuidCacheKey cacheKey(calId, E_EVENT, QString::fromStdString(guid));
    if (m_dbCache->containsEventVector(cacheKey))
    {
        // found in cache
        m_dbCache->takeEventVector(cacheKey, listEvent);
        return listEvent;
    }

    const int columnNumber = 49;
    CEvent *event = 0;
    CAlarm *pAlarm = 0;
    CRecurrence *pRec = 0;
    int iI_EventCount = 0;
    int iJ_EventCount = 0;
    pErrorCode = CALENDAR_OPERATION_SUCCESSFUL;
    std::vector<long> vCookie;
    std::vector<std::string> vERule;
    std::vector<std::string> vEdate;
    std::vector<std::string> vRdate;
    std::vector<std::string> vRRule;

    QSqlQuery pQuery;
    if (!pQuery.prepare(selectInnerJoinBatchGuid)) {
        pErrorCode = CALENDAR_DATABASE_ERROR;
        return listEvent;
    }
    pQuery.bindValue(":calId", QString::number(calId));
    pQuery.bindValue(":compType", QString::number(E_EVENT));
    pQuery.bindValue(":compUid", QString::fromStdString(guid));

    bool ok = pQuery.exec();

    sqliteErrorMapper(pQuery.lastError(), pErrorCode);
    if (!ok)
        return listEvent;

    while (pQuery.next()) {
        event = new CEvent();
        pAlarm = new CAlarm();
        pRec = new CRecurrence();
        for (iJ_EventCount = 0; iJ_EventCount < columnNumber; ++iJ_EventCount) {
            switch(iJ_EventCount) {
            case 0: // ID1
                event->setId(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 1:
                break;

            case 2: // ID3
                event->setType(pQuery.value(iJ_EventCount).toInt());
                break;

            case 3: // ID4
                event->setFlags(pQuery.value(iJ_EventCount).toInt());
                break;

            case 4: // ID5
                event->setDateStart(pQuery.value(iJ_EventCount).toInt());
                break;

            case 5: // ID6
                event->setDateEnd(pQuery.value(iJ_EventCount).toInt());
                break;

            case 6: // ID7
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setSummary(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 7: // ID8
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setLocation(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 8: // ID9
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setDescription(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 9: // ID10
                event->setStatus(pQuery.value(iJ_EventCount).toInt());
                break;

            case 10: // ID11
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setGUid(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 11: // ID12
                event->setUntil(pQuery.value(iJ_EventCount).toInt());
                break;

            case 12: // ID13
                event->setAllDay(pQuery.value(iJ_EventCount).toInt());
                break;

            case 13: // ID14
                event->setCreatedTime(pQuery.value(iJ_EventCount).toInt());
                break;

            case 14: // ID15
                event->setLastModified(pQuery.value(iJ_EventCount).toInt());
                break;

            case 15: // ID16
                event->setTzid(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 16: // ID17
            case 17: // ID18
            case 18: // ID19
                break;

            case 19: // ID20
                if (pQuery.value(iJ_EventCount).toInt())
                    event->setClas(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 20: // ID21
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setGeo(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 21: // ID22
                event->setPriority(pQuery.value(iJ_EventCount).toInt());
                break;

            case 22: // ID23
                event->setDateStamp(pQuery.value(iJ_EventCount).toInt());
                break;

            case 23: // ID24
                event->setSequence(pQuery.value(iJ_EventCount).toInt());
                break;

            case 24: // ID25
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setTransparency(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 25: // ID26
                event->setUid(pQuery.value(iJ_EventCount).toInt());
                break;

            case 26: // ID27
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setUrl(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 27: // ID28
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    std::vector<std::string> vAtt;
                    vAtt.push_back(pQuery.value(iJ_EventCount).toString().toStdString());
                    event->setAttachments(vAtt);
                }
                break;

            case 28: // ID29
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setCategories(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 29: // ID30
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setComments(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 30: // ID31
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setContact(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 31: // ID32
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setRelated(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 32: // ID33
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    event->setResources(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 33: // ID34
            case 34: // ID35
            case 35: // ID36
                break;

            case 36: // ID37
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pAlarm->setTrigger(pQuery.value(iJ_EventCount).toInt());
                break;

            case 37: // ID38
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pAlarm->setRepeat(pQuery.value(iJ_EventCount).toInt());
                break;

            case 38: // ID39
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pAlarm->setDuration(pQuery.value(iJ_EventCount).toInt());
                break;

            case 39: // ID40
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pAlarm->setAction(pQuery.value(iJ_EventCount).toInt());
                break;

            case 40: // ID41
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    vCookie.push_back(pQuery.value(iJ_EventCount).toInt());
                    pAlarm->setCookie(vCookie);
                }
                break;

            case 41: // ID42
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pAlarm->setAttach(pQuery.value(iJ_EventCount).toString().toStdString());
                break;

            case 42: // ID43
                break;

            case 43: // ID44
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    vRRule = event->extractSubStrings(pQuery.value(iJ_EventCount).toString().toStdString(), EXCLAMATION);
                    pRec->setRrule(vRRule);
                }
                break;

            case 44: // ID45
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    vRdate = event->extractSubStrings(pQuery.value(iJ_EventCount).toString().toStdString(), SEMI_COLON);
                    pRec->setRDays(vRdate);
                }
                break;

            case 45: // ID46
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    vEdate = event->extractSubStrings(pQuery.value(iJ_EventCount).toString().toStdString(), SEMI_COLON);
                    pRec->setEDays(vEdate);
                }
                break;

            case 46: // ID47
                if (!pQuery.value(iJ_EventCount).toString().isEmpty()) {
                    vERule = event->extractSubStrings(pQuery.value(iJ_EventCount).toString().toStdString(), EXCLAMATION);
                    pRec->setErule(vERule);
                }
                break;

            case 47: // ID48
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pRec->setRecurId(pQuery.value(iJ_EventCount).toInt());
                break;

            case 48: // ID49
                if (!pQuery.value(iJ_EventCount).toString().isEmpty())
                    pRec->setRtype(pQuery.value(iJ_EventCount).toInt());
                break;
            }
        }

        if ((event->getFlags() == HAS_RECURRENCE) ||
            (event->getFlags() == HAS_RECURRENCE_ALARM)) {
            event->setRecurrence(pRec);
        }
        delete pRec;
        pRec = 0;

        if ((event->getFlags() == HAS_ALARM) ||
            (event->getFlags() == HAS_RECURRENCE_ALARM)) {
            event->setAlarm(pAlarm);
        }
        delete pAlarm;
        pAlarm = 0;

        std::vector<CAttendee *> listAttendee;

        listAttendee = event->retrieveAttendeeDetails();
        COrganizer *pOrg = 0;

        pOrg = event->retrieveOrganizerDetails();
        if (listAttendee.size())
            event->setAttendees(listAttendee);

        std::vector<CAttendee *>::iterator listAttendeeIterator;
        for (listAttendeeIterator = listAttendee.begin(); listAttendeeIterator != listAttendee.end(); ++listAttendeeIterator)
            delete *listAttendeeIterator;

        if (pOrg) {
            event->setOrganizer(pOrg);
            delete pOrg;
            pOrg = 0;
        }

        /*retrieve xprop */
        std::vector<CProperties *> vPropList;
        vPropList = event->retrieveXPropertyDetails();
        event->setXProperties(vPropList);

        std::vector<CProperties *>::iterator vPropListIterator;
        for (vPropListIterator = vPropList.begin(); vPropListIterator != vPropList.end(); ++vPropListIterator)
            delete *vPropListIterator;

        /*retrieve params */
        std::map<std::string, std::vector<CParameters *> > paramMap;
        paramMap = event->retrieveParameterDetails();

        event->setHashMap(paramMap);
        paramMap.clear();

        /* push the event in to the list */
        listEvent.push_back(event);

        ++iI_EventCount;
    }

    // put to cache
    m_dbCache->insertEventVector(cacheKey, listEvent);

    return listEvent;
}
Esempio n. 25
0
void
COSXScreen::handleSystemEvent(const CEvent& event, void*)
{
	EventRef* carbonEvent = reinterpret_cast<EventRef*>(event.getData());
	assert(carbonEvent != NULL);

	UInt32 eventClass = GetEventClass(*carbonEvent);

	switch (eventClass) {
	case kEventClassMouse:
		switch (GetEventKind(*carbonEvent)) {
		case kSynergyEventMouseScroll:
		{
			OSStatus r;
			long xScroll;
			long yScroll;

			// get scroll amount
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisX,
					typeLongInteger,
					NULL,
					sizeof(xScroll),
					NULL,
					&xScroll);
			if (r != noErr) {
				xScroll = 0;
			}
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisY,
					typeLongInteger,
					NULL,
					sizeof(yScroll),
					NULL,
					&yScroll);
			if (r != noErr) {
				yScroll = 0;
			}

			if (xScroll != 0 || yScroll != 0) {
				onMouseWheel(-mapScrollWheelToSynergy(xScroll),
								mapScrollWheelToSynergy(yScroll));
			}
		}
		}
		break;

	case kEventClassKeyboard: 
			switch (GetEventKind(*carbonEvent)) {
				case kEventHotKeyPressed:
				case kEventHotKeyReleased:
					onHotKey(*carbonEvent);
					break;
			}
			
			break;
			
	case kEventClassWindow:
		SendEventToWindow(*carbonEvent, m_userInputWindow);
		switch (GetEventKind(*carbonEvent)) {
		case kEventWindowActivated:
			LOG((CLOG_DEBUG1 "window activated"));
			break;

		case kEventWindowDeactivated:
			LOG((CLOG_DEBUG1 "window deactivated"));
			break;

		case kEventWindowFocusAcquired:
			LOG((CLOG_DEBUG1 "focus acquired"));
			break;

		case kEventWindowFocusRelinquish:
			LOG((CLOG_DEBUG1 "focus released"));
			break;
		}
		break;

	default:
		SendEventToEventTarget(*carbonEvent, GetEventDispatcherTarget());
		break;
	}
}
Esempio n. 26
0
void
CStreamFilter::filterEvent(const CEvent& event)
{
    EVENTQUEUE->dispatchEvent(CEvent(event.getType(),
                                     getEventTarget(), event.getData()));
}
Esempio n. 27
0
//-----------------------------------------
//
// Run PortalFlow across all available processing nodes
//
void RunMPIPortalFlow()
{
    Msg( "%-20s ", "MPIPortalFlow:" );
	if ( g_bMPIMaster )
		StartPacifier("");

	// Workers wait until we get the MC socket address.
	g_PortalMCThreadUniqueID = StatsDB_GetUniqueJobID();
	if ( g_bMPIMaster )
	{
		CCycleCount cnt;
		cnt.Sample();
		CUniformRandomStream randomStream;
		randomStream.SetSeed( cnt.GetMicroseconds() );

		g_PortalMCAddr.port = randomStream.RandomInt( 22000, 25000 ); // Pulled out of something else.
		g_PortalMCAddr.ip[0] = (unsigned char)RandomInt( 225, 238 );
		g_PortalMCAddr.ip[1] = (unsigned char)RandomInt( 0, 255 );
		g_PortalMCAddr.ip[2] = (unsigned char)RandomInt( 0, 255 );
		g_PortalMCAddr.ip[3] = (unsigned char)RandomInt( 3, 255 );

		g_pPortalMCSocket = CreateIPSocket();
		int i=0;
		for ( i; i < 5; i++ )
		{
			if ( g_pPortalMCSocket->BindToAny( randomStream.RandomInt( 20000, 30000 ) ) )
				break;
		}
		if ( i == 5 )
		{
			Error( "RunMPIPortalFlow: can't open a socket to multicast on." );
		}

		char cPacketID[2] = { VMPI_VVIS_PACKET_ID, VMPI_SUBPACKETID_MC_ADDR };
		VMPI_Send2Chunks( cPacketID, sizeof( cPacketID ), &g_PortalMCAddr, sizeof( g_PortalMCAddr ), VMPI_PERSISTENT );
	}
	else
	{
		VMPI_SetCurrentStage( "wait for MC address" );

		while ( !g_bGotMCAddr )
		{
			VMPI_DispatchNextMessage();
		}

		// Open our multicast receive socket.
		g_pPortalMCSocket = CreateMulticastListenSocket( g_PortalMCAddr );
		if ( !g_pPortalMCSocket )
		{
			char err[512];
			IP_GetLastErrorString( err, sizeof( err ) );
			Error( "RunMPIPortalFlow: CreateMulticastListenSocket failed. (%s).", err );
		}

		// Make a thread to listen for the data on the multicast socket.
		DWORD dwDummy = 0;
		g_MCThreadExitEvent.Init( false, false );

		// Make sure we kill the MC thread if the app exits ungracefully.
		CmdLib_AtCleanup( MCThreadCleanupFn );
		
		g_hMCThread = CreateThread( 
			NULL,
			0,
			PortalMCThreadFn,
			NULL,
			0,
			&dwDummy );

		if ( !g_hMCThread )
		{
			Error( "RunMPIPortalFlow: CreateThread failed for multicast receive thread." );
		}			
	}

	VMPI_SetCurrentStage( "RunMPIBasePortalFlow" );


	g_pDistributeWorkCallbacks = &g_VisDistributeWorkCallbacks;

	g_CPUTime.Init();
	double elapsed = DistributeWork( 
		g_numportals * 2,		// # work units
		VMPI_DISTRIBUTEWORK_PACKETID,	// packet ID
		ProcessPortalFlow,		// Worker function to process work units
		ReceivePortalFlow		// Master function to receive work results
		);
		
	g_pDistributeWorkCallbacks = NULL;

	CheckExitedEarly();

	// Stop the multicast stuff.
	VMPI_DeletePortalMCSocket();

	if( !g_bMPIMaster )
	{
		if ( g_iVMPIVerboseLevel >= 1 )
		{
			Msg( "Received %d (out of %d) portals from multicast.\n", g_nMulticastPortalsReceived, g_numportals * 2 );
			Msg( "%.1f%% CPU utilization during PortalFlow\n", (g_CPUTime.GetSeconds() * 100.0f / elapsed) / numthreads );
		}

		Msg( "VVIS worker finished. Over and out.\n" );
		VMPI_SetCurrentStage( "worker done" );

		CmdLib_Exit( 0 );
	}

	if ( g_bMPIMaster )
	{
		EndPacifier( false );
		Msg( " (%d)\n", (int)elapsed );
	}
}
Esempio n. 28
0
int CecKeyPress(void *UNUSED(cbParam), const cec_keypress &key)
{
  g_lastKey = key.keycode;
  g_keyEvent.Signal();
  return 0;
}
Esempio n. 29
0
void CModelExpansion::duplicateEvent(CEvent* source, const std::string & index, const SetOfModelElements & sourceSet, ElementsMap & emap)
{
  //if the source object has already been duplicated: do nothing
  if (emap.exists(source))
    return;

  CEvent* newObj = NULL;

  if (expressionContainsObject(source->getTriggerExpressionPtr(), sourceSet)
      || expressionContainsObject(source->getDelayExpressionPtr(), sourceSet))
    {
      //we need to duplicate the event itself (because the trigger refers to a duplicated object)

      //try creating the object until we find a name that is not yet used
      std::ostringstream infix;

      do
        {
          std::ostringstream name;
          name << source->getObjectName() << infix.str() << index;
          newObj = mpModel->createEvent(name.str());
          infix << "_";
        }
      while (!newObj);

      //add duplicated object to the map
      emap.add(source, newObj);

      //now do the trigger
      newObj->setTriggerExpression(source->getTriggerExpression());
      newObj->getTriggerExpressionPtr()->compile(); //I don't know why this is necessary
      updateExpression(newObj->getTriggerExpressionPtr(), index, sourceSet, emap);

      //delay
      newObj->setDelayExpression(source->getDelayExpression());
      newObj->getDelayExpressionPtr()->compile(); //I don't know why this is necessary
      updateExpression(newObj->getDelayExpressionPtr(), index, sourceSet, emap);

      newObj->setDelayAssignment(source->getDelayAssignment());
    }
  else
    {
      newObj = source; //no copying necessary

      //add duplicated object to the map
      emap.add(source, newObj);
    }

  //now the event assignments...
  size_t i;

  for (i = 0; i < source->getAssignments().size(); ++i)
    {
      const CEventAssignment* pSourceAssignment = source->getAssignments()[i];

      //const CModelEntity * pSourceTarget = dynamic_cast<const CModelEntity * >(CCopasiRootContainer::getKeyFactory()->get(pSourceAssignment->getTargetKey()));
      if (sourceSet.contains(pSourceAssignment->getTargetKey()))
        {
          //we assume that the duplicate of the target object already exists.
          //this should be true since events are duplicated last.
          if (!emap.exists(pSourceAssignment->getTargetKey()))
            continue;

          //create duplicate of assignment (this can be either in the original event or in the
          //duplicate of an event)
          CEventAssignment * pNewAssignment = new CEventAssignment(emap.getDuplicateKey(pSourceAssignment->getTargetKey()));
          newObj->getAssignments().add(pNewAssignment, true);

          //we do an assumption:
          //It should not happen that the assignment expression contains a reference to an object that is duplicated,
          //but the assignment target is not duplicated.

          //now copy the expression
          pNewAssignment->setExpression(pSourceAssignment->getExpression());
          pNewAssignment->getExpressionPtr()->compile();
          updateExpression(pNewAssignment->getExpressionPtr(), index, sourceSet, emap);
        }
    }

  newObj->setNotes(source->getNotes());
  newObj->setMiriamAnnotation(source->getMiriamAnnotation(), newObj->getKey(), source->getKey());
}
Esempio n. 30
0
//只能开启一个交易线程,否则同步可能出现问题
UINT TradeEntry_00(LPVOID pParam)//启动入口,作为一个独立的线程
{
	CThostFtdcQryInstrumentField req;
	memset(&req, 0, sizeof(req));
	strcpy(req.InstrumentID, INSTRUMENT_ID);
	::EnterCriticalSection(&REQUEST_ID_IF);
	int iResult = pUserApi->ReqQryInstrument(&req, ++iRequestID);
	::LeaveCriticalSection(&REQUEST_ID_IF);

	CThostFtdcQryInvestorPositionField req00;
	memset(&req00, 0, sizeof(req00));
	strcpy(req00.BrokerID, BROKER_ID);
	strcpy(req00.InvestorID, INVESTOR_ID);
	strcpy(req00.InstrumentID, INSTRUMENT_ID);
	::EnterCriticalSection(&REQUEST_ID_IF);
	iResult = pUserApi->ReqQryInvestorPosition(&req00, ++iRequestID);
	::LeaveCriticalSection(&REQUEST_ID_IF);

#ifdef _debug
	iNextOrderRef++;//测试
	ifAsk1 = 2180;//
	IfInData *data;//测试
	data = new IfInData(1,false,true,iNextOrderRef); //测试
	AfxBeginThread(IfEntry,data,THREAD_PRIORITY_NORMAL,0,0,NULL);//测试
	return 0;//测试
#endif
	if(clientDlg == NULL){
		return -1;
	}
	if(pUserApi == NULL){
		return -1;
	}	
	//从对话框初始化
	step = clientDlg->m_step;
	multiply = clientDlg->m_multiply;
	aimOfLadder = clientDlg->m_aimOfLadder;
	datumDiff = clientDlg->m_DeltaDatumDiff + clientDlg->m_datumDiff;
	HoldAndDirec tempIni;
	tempIni.price = clientDlg->m_costINI - datumDiff;//持仓相对价格
	tempIni.numDirec = clientDlg->m_numINI;//带有方向的持仓
	holdHedge.push_back(tempIni);
	netHold = tempIni.numDirec;
	//溢价和基差计算
	while(true){
		UpdateTrade.Lock(INFINITE);//事件触发
		//获取系统时间
		//SYSTEMTIME sys;
		//GetLocalTime(&sys);
		CString PREMIUM;	
		calDeviation();
		deviationHigh_save = deviationHigh;
		deviationLow_save = deviationLow;
		PREMIUM.Format(_T("%.4f"),premiumLow);	
		clientDlg->SetDlgItemTextA(IDC_EDIT18,PREMIUM);
		PREMIUM.Format(_T("%.4f"),premiumHigh);	
		clientDlg->SetDlgItemTextA(IDC_EDIT16,PREMIUM);
		/*
		//非交易日返回
		if(!isTradeDay(sys.wYear,sys.wMonth,sys.wDay))
		{
		continue;
		}
		//非常规交易时间
		if((sys.wHour == 9 && sys.wMinute < 10) || 
		(sys.wHour == 15 && sys.wMinute > 15) ||
		(sys.wHour == 11 && sys.wMinute > 30) ||
		(sys.wHour == 12)||
		(sys.wHour < 9) || (sys.wHour > 15)){
		continue;
		}
		*/
		if(clientDlg->tradeEnd){//终止
			//做清空处理,重新启动时会初始化
			holdHedge.clear();
			netHold = 0;
			return -1;
		}
		if(clientDlg->stop){//暂停
			continue;
		}
		if(_isnan(datumDiff) != 0 || _isnan(premium)!=0 ||_isnan(deviation)!=0){
			continue;//判断非零值错误
		}
		::EnterCriticalSection(&g_A50Price);
		::EnterCriticalSection(&g_IfPrice);
		::EnterCriticalSection(&g_index);
		if(a50Bid1 < 1 || a50Ask1 < 1 || ifAsk1 < 1 || ifBid1 < 1 || A50Index < 1 || HS300Index < 1){
			::LeaveCriticalSection(&g_IfPrice);
			::LeaveCriticalSection(&g_A50Price);
			::LeaveCriticalSection(&g_index);;
			continue;
		}
		else{
			::LeaveCriticalSection(&g_IfPrice);
			::LeaveCriticalSection(&g_A50Price);
			::LeaveCriticalSection(&g_index);
		}
		if(fabs(premium) > 300 || fabs(premium) < 0.01){
			continue;//排除开盘时有可能报价不全导致的错误溢价计算
		}
		if(deviation >= 0){
#ifdef _case1
			//临时用multiply代替需要的合约数目,因为现在只有一手,保证成交
			if(a50Bid1Size >= multiply * 1){
				ladder = (int)(deviationLow / step);
			}
			else{
				continue;
			}
#else
			ladder = (int)((deviationLow + 2.5) / step);
#endif
		}
		else{
#ifdef _case1
			//临时用multiply代替需要的合约数目,因为现在只有一手,保证成交
			if(a50Ask1Size >= multiply * 1){
				ladder = -(int)(-deviationHigh / step);
			}
			else{
				continue;
			}
#else
			ladder = -(int)((-deviationHigh + 2.5) / step);
#endif
		}
		if(ladder > 1){
			ladder = 1;
		}
		else if(ladder < -1){
			ladder = -1;
		}
		needHold = aimOfLadder * ladder;//需要的合约与偏差的关系,可以根据资金量进行修改
#ifdef _case1
		profitTarget = step;
#else
		profitTarget = step - 2.5;
#endif
		double profitUnit = 0;
		int needBuyFlat = 0,needSellFlat = 0;//始终大于0的,无正负
		double totalTradingValue = 0;//准备交易的总价值
		for(unsigned int j = 0;j < holdHedge.size();j++){
			itHedge = holdHedge.begin() + j;
			//if(itHedge->numDirec < 0){//其实只要nethold为负,就保证了所有的numDirec为负,不存在既有numDirec为正,又有为负的情况
			if(netHold < 0){
				profitUnit = itHedge->price - deviationHigh;
				if(profitUnit >= profitTarget){
					needBuyFlat = needBuyFlat - itHedge->numDirec;
					totalTradingValue = totalTradingValue + itHedge->price * (-itHedge->numDirec);
					//更新记录
					netHold = netHold - itHedge->numDirec;
					holdHedge.erase(itHedge);
					j--;//出现删除操作时,需要将指针向前倒退
				}
			}
			//else if(itHedge->numDirec > 0)
			else if(netHold > 0){
				profitUnit = -(itHedge->price - deviationLow);
				if(profitUnit >= profitTarget){
					needSellFlat = needSellFlat + itHedge->numDirec;
					totalTradingValue = totalTradingValue + itHedge->price * itHedge->numDirec;
					//更新记录
					netHold = netHold - itHedge->numDirec;
					holdHedge.erase(itHedge);
					j--;
				}
			}
			else{
				//等于0时什么也不做
			}
		}
		//平仓操作,,其实买平和卖平一定只有一个得到执行的,否则便出现了问题
		flatOrOpen(needBuyFlat,true,true);
		flatOrOpen(needSellFlat,false,true);
		//开仓操作
		BS(needHold,netHold);
	}
	return 0;//根本走不到这儿
}