Exemple #1
0
boolean
TxCache::add(uint64 checksum, GHQTexInfo *info, int dataSize)
{
	/* NOTE: dataSize must be provided if info->data is zlib compressed. */

	if (!checksum || !info->data) return 0;

	uint8 *dest = info->data;
	uint32 format = info->format;

	if (!dataSize) {
		dataSize = TxUtil::sizeofTx(info->width, info->height, info->format);

		if (!dataSize) return 0;

		if (_options & (GZ_TEXCACHE|GZ_HIRESTEXCACHE)) {
			/* zlib compress it. compression level:1 (best speed) */
			uLongf destLen = _gzdestLen;
			dest = (dest == _gzdest0) ? _gzdest1 : _gzdest0;
			if (compress2(dest, &destLen, info->data, dataSize, 1) != Z_OK) {
				dest = info->data;
				DBG_INFO(80, wst("Error: zlib compression failed!\n"));
			} else {
				DBG_INFO(80, wst("zlib compressed: %.02fkb->%.02fkb\n"), (float)dataSize/1000, (float)destLen/1000);
				dataSize = destLen;
				format |= GL_TEXFMT_GZ;
			}
		}
	}

	/* if cache size exceeds limit, remove old cache */
	if (_cacheSize > 0) {
		_totalSize += dataSize;
		if ((_totalSize > _cacheSize) && !_cachelist.empty()) {
			/* _cachelist is arranged so that frequently used textures are in the back */
			std::list<uint64>::iterator itList = _cachelist.begin();
			while (itList != _cachelist.end()) {
				/* find it in _cache */
				std::map<uint64, TXCACHE*>::iterator itMap = _cache.find(*itList);
				if (itMap != _cache.end()) {
					/* yep we have it. remove it. */
					_totalSize -= (*itMap).second->size;
					free((*itMap).second->info.data);
					delete (*itMap).second;
					_cache.erase(itMap);
				}
				itList++;

				/* check if memory cache has enough space */
				if (_totalSize <= _cacheSize)
					break;
			}
			/* remove from _cachelist */
			_cachelist.erase(_cachelist.begin(), itList);

			DBG_INFO(80, wst("+++++++++\n"));
		}
		_totalSize -= dataSize;
	}

	/* cache it */
	uint8 *tmpdata = (uint8*)malloc(dataSize);
	if (tmpdata) {
		TXCACHE *txCache = new TXCACHE;
		if (txCache) {
			/* we can directly write as we filter, but for now we get away
	   * with doing memcpy after all the filtering is done.
	   */
			memcpy(tmpdata, dest, dataSize);

			/* copy it */
			memcpy(&txCache->info, info, sizeof(GHQTexInfo));
			txCache->info.data = tmpdata;
			txCache->info.format = format;
			txCache->size = dataSize;

			/* add to cache */
			if (_cacheSize > 0) {
				_cachelist.push_back(checksum);
				txCache->it = --(_cachelist.end());
			}
			/* _cache[checksum] = txCache; */
			_cache.insert(std::map<uint64, TXCACHE*>::value_type(checksum, txCache));

#ifdef DEBUG
			DBG_INFO(80, wst("[%5d] added!! crc:%08X %08X %d x %d gfmt:%x total:%.02fmb\n"),
					 _cache.size(), (uint32)(checksum >> 32), (uint32)(checksum & 0xffffffff),
					 info->width, info->height, info->format & 0xffff, (float)_totalSize/1000000);

			if (_cacheSize > 0) {
				DBG_INFO(80, wst("cache max config:%.02fmb\n"), (float)_cacheSize/1000000);

				if (_cache.size() != _cachelist.size()) {
					DBG_INFO(80, wst("Error: cache/cachelist mismatch! (%d/%d)\n"), _cache.size(), _cachelist.size());
				}
			}
#endif

			/* total cache size */
			_totalSize += dataSize;

			return 1;
		}
		free(tmpdata);
	}

	return 0;
}
intptr_t RenderServer::main()
{
    RenderThreadsSet threads;

    while(1) {
        SocketStream *stream = m_listenSock->accept();
        if (!stream) {
            fprintf(stderr,"Error accepting connection, aborting\n");
            break;
        }

        unsigned int clientFlags;
        if (!stream->readFully(&clientFlags, sizeof(unsigned int))) {
            fprintf(stderr,"Error reading clientFlags\n");
            delete stream;
            continue;
        }

        DBG("RenderServer: Got new stream!\n");

        // check if we have been requested to exit while waiting on accept
        if ((clientFlags & IOSTREAM_CLIENT_EXIT_SERVER) != 0) {
            m_exiting = true;
            break;
        }

        RenderThread *rt = RenderThread::create(stream, &m_lock);
        if (!rt) {
            fprintf(stderr,"Failed to create RenderThread\n");
            delete stream;
            stream = NULL;
        } else if (!rt->start()) {
            fprintf(stderr,"Failed to start RenderThread\n");
            delete rt;
            rt = NULL;
        }

        //
        // remove from the threads list threads which are
        // no longer running
        //
        for (RenderThreadsSet::iterator n,t = threads.begin();
             t != threads.end();
             t = n) {
            // first find next iterator
            n = t;
            n++;

            // delete and erase the current iterator
            // if thread is no longer running
            if ((*t)->isFinished()) {
                delete (*t);
                threads.erase(t);
            }
        }

        // if the thread has been created and started, insert it to the list
        if (rt) {
            threads.insert(rt);
            DBG("Started new RenderThread\n");
        }
    }

    //
    // Wait for all threads to finish
    //
    for (RenderThreadsSet::iterator t = threads.begin();
         t != threads.end();
         t++) {
        (*t)->wait(NULL);
        delete (*t);
    }
    threads.clear();

    //
    // de-initialize the FrameBuffer object
    //
    FrameBuffer::finalize();
    return 0;
}
// ---------------------------------------------------------------------------
// 
// ------------
void destroy(bGenericXMLBaseElement *elt){
//bTrace trc("lib::destroy",false);
//trc.msg("parent instance (%x) of %s deleted",elt,"bCalcCNbParts");
	delete (bCalcCNbParts*)(void*)elt;
}
Exemple #4
0
ViewElementList::~ViewElementList()
{
    for (iterator i = begin(); i != end(); ++i) {
        delete (*i);
    }
}
QTD_EXTERN QTD_EXPORT void qtd_QDesktopServices_delete(void* nativeId)
{
    delete (QDesktopServices_QtDShell*)nativeId;
}
Exemple #6
0
void genetics::select(int chunk, int nBiasWheel, double mutFactor, double crossOverFactor, int nCpy) {

    for(int it = 0; it<nNets; it+=chunk) {
        RandomList *rl = new RandomList(nNets);
        int* mixedArray = rl->GetMixedArray();
        biasWheel *bw = new biasWheel(nBiasWheel);
        //printf("===== Selection =====\n");
        for(int i = 0; i < nBiasWheel; i++) {
            int ind = mixedArray[i];
            //printf("%1.5f\n",1-meanErr[ind]);
            bw->addObject(nets[ind],1-meanErr[ind],ind);
        }
        //printf("=====================\n");
        //bw->print();

#ifdef BIASWHEEL_STATS
        int *selectionIndexes = (int*) malloc (sizeof(int)*nNets);
        double *selectionProb = (double*) malloc (sizeof(double)*nNets);
        for(int p = 0; p<nNets; p++) {
            selectionIndexes[p] = 0;
            selectionProb[p] = 0.0;
        }
#endif

        for(int k = 0; k<chunk; k+=2) {
            biasWheel::couple c;
            bw->electCouple(&c);

            //printf("Couple elected %p %p\n",c.A,c.B);

            network *mom = (network*)c.A;
            network *dad = (network*)c.B;

#ifdef BIASWHEEL_STATS
            printf("%03d %03d %1.6f %1.6f\n",c.iA,c.iB,c.pA,c.pB);
            selectionIndexes[c.iA]++;
            selectionIndexes[c.iB]++;

            selectionProb[c.iA] = c.pA;
            selectionProb[c.iB] = c.pB;
#endif
            lovemaking(mom, dad, childNets[it+k], childNets[it+k+1], mutFactor, crossOverFactor);
        }

        // TODO Copy the N best elements into child population
        mixedArray = rl->GetMixedArray();
        for(int i = 0; i<nCpy; i++) {
            int ind = mixedArray[i];
            double *top = nets[i]->extractGenome(false);
            childNets[ind]->setGenome(top);
            free(top);
        }

        // Alternate between child an parents
        for(int i = 0; i<nNets; i++) {
            network *tmp = nets[i];
            if(tmp == NULL) {
                printf("%d #YOLO MAIS YOLO\n",i);
                while(1);
            }
            nets[i] = childNets[i];
            childNets[i] = tmp;
        }

#ifdef BIASWHEEL_STATS
        printf("--BW_STATS-\n");
        for(int i = 0; i< nNets; i++) {
            if(selectionProb[i] != 0.0)
                printf("%03d;%1.5f\n",selectionIndexes[i],selectionProb[i]);
        }

        free(selectionIndexes);
        free(selectionProb);
#endif
        delete(bw);
        delete(rl);
    }
}
Exemple #7
0
// Free memory associated with a ScreenRef
void		DisposeScreenRef( ScreenRef display )
{
	delete (RLDisplay *) display;
}
Exemple #8
0
QTCEXPORT(void,qtc_QTextCharFormat_delete)(void* x0) {
  delete((QTextCharFormat*)x0);
}
Exemple #9
0
int main(int argc, char** argv) {
  std::cout << "Blackbird Bitcoin Arbitrage" << std::endl;
  std::cout << "DISCLAIMER: USE THE SOFTWARE AT YOUR OWN RISK\n" << std::endl;

  std::locale mylocale("");

  Parameters params("blackbird.conf");

  if (!params.demoMode) {
    if (!params.useFullCash) {
      if (params.cashForTesting < 10.0) {
        std::cout << "WARNING: Minimum test cash recommended: $10.00\n" << std::endl;
      }
      if (params.cashForTesting > params.maxExposure) {
        std::cout << "ERROR: Test cash ($" << params.cashForTesting << ") is above max exposure ($" << params.maxExposure << ")\n" << std::endl;
        return -1;
      }
    }
  }

  if (params.useDatabase) {
    if (createDbConnection(params) != 0) {
      std::cout << "ERROR: cannot connect to the database \'" << params.dbName << "\'\n" << std::endl;
      return -1;
    }
  }

  getQuoteType getQuote[10];
  getAvailType getAvail[10];
  sendOrderType sendOrder[10];
  isOrderCompleteType isOrderComplete[10];
  getActivePosType getActivePos[10];
  getLimitPriceType getLimitPrice[10];
  std::string dbTableName[10];
  int index = 0;

  if (params.bitfinexApi.empty() == false || params.demoMode == true) {
    params.addExchange("Bitfinex", params.bitfinexFees, params.bitfinexCanShort, true);
    getQuote[index] = Bitfinex::getQuote;
    getAvail[index] = Bitfinex::getAvail;
    sendOrder[index] = Bitfinex::sendOrder;
    isOrderComplete[index] = Bitfinex::isOrderComplete;
    getActivePos[index] = Bitfinex::getActivePos;
    getLimitPrice[index] = Bitfinex::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "bitfinex";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.okcoinApi.empty() == false || params.demoMode == true) {
    params.addExchange("OKCoin", params.okcoinFees, params.okcoinCanShort, true);
    getQuote[index] = OkCoin::getQuote;
    getAvail[index] = OkCoin::getAvail;
    sendOrder[index] = OkCoin::sendOrder;
    isOrderComplete[index] = OkCoin::isOrderComplete;
    getActivePos[index] = OkCoin::getActivePos;
    getLimitPrice[index] = OkCoin::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "okcoin";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.bitstampClientId.empty() == false || params.demoMode == true) {
    params.addExchange("Bitstamp", params.bitstampFees, params.bitstampCanShort, true);
    getQuote[index] = Bitstamp::getQuote;
    getAvail[index] = Bitstamp::getAvail;
    sendOrder[index] = Bitstamp::sendOrder;
    isOrderComplete[index] = Bitstamp::isOrderComplete;
    getActivePos[index] = Bitstamp::getActivePos;
    getLimitPrice[index] = Bitstamp::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "bitstamp";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.geminiApi.empty() == false || params.demoMode == true) {
    params.addExchange("Gemini", params.geminiFees, params.geminiCanShort, true);
    getQuote[index] = Gemini::getQuote;
    getAvail[index] = Gemini::getAvail;
    sendOrder[index] = Gemini::sendOrder;
    isOrderComplete[index] = Gemini::isOrderComplete;
    getActivePos[index] = Gemini::getActivePos;
    getLimitPrice[index] = Gemini::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "gemini";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.krakenApi.empty() == false || params.demoMode == true) {
    params.addExchange("Kraken", params.krakenFees, params.krakenCanShort, true);
    getQuote[index] = Kraken::getQuote;
    getAvail[index] = Kraken::getAvail;
    sendOrder[index] = Kraken::sendOrder;
    isOrderComplete[index] = Kraken::isOrderComplete;
    getActivePos[index] = Kraken::getActivePos;
    getLimitPrice[index] = Kraken::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "kraken";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.itbitApi.empty() == false || params.demoMode == true) {
    params.addExchange("ItBit", params.itbitFees, params.itbitCanShort, false);
    getQuote[index] = ItBit::getQuote;
    getAvail[index] = ItBit::getAvail;
    // sendOrder[index] = ItBit::sendOrder;
    // isOrderComplete[index] = ItBit::isOrderComplete;
    getActivePos[index] = ItBit::getActivePos;
    getLimitPrice[index] = ItBit::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "itbit";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.btceApi.empty() == false || params.demoMode == true) {
    params.addExchange("BTC-e", params.btceFees, params.btceCanShort, false);
    getQuote[index] = BTCe::getQuote;
    getAvail[index] = BTCe::getAvail;
    // sendOrder[index] = BTCe::sendOrder;
    // isOrderComplete[index] = BTCe::isOrderComplete;
    getActivePos[index] = BTCe::getActivePos;
    getLimitPrice[index] = BTCe::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "btce";
      createTable(dbTableName[index], params);
    }
    index++;
  }
  if (params.sevennintysixApi.empty() == false || params.demoMode == true) {
    params.addExchange("796.com", params.sevennintysixFees, params.sevennintysixCanShort, true);
    getQuote[index] = SevenNintySix::getQuote;
    getAvail[index] = SevenNintySix::getAvail;
    sendOrder[index] = SevenNintySix::sendOrder;
    isOrderComplete[index] = SevenNintySix::isOrderComplete;
    getActivePos[index] = SevenNintySix::getActivePos;
    getLimitPrice[index] = SevenNintySix::getLimitPrice;
    if (params.useDatabase) {
      dbTableName[index] = "796_com";
      createTable(dbTableName[index], params);
    }
    index++;
  }


  if (index < 2) {
    std::cout << "ERROR: Blackbird needs at least two Bitcoin exchanges. Please edit the config.json file to add new exchanges\n" << std::endl;
    return -1;
  }

  std::string currDateTime = printDateTimeFileName();
  std::string csvFileName = "blackbird_result_" + currDateTime + ".csv";
  std::ofstream csvFile;
  csvFile.open(csvFileName.c_str(), std::ofstream::trunc);
  csvFile << "TRADE_ID,EXCHANGE_LONG,EXHANGE_SHORT,ENTRY_TIME,EXIT_TIME,DURATION,TOTAL_EXPOSURE,BALANCE_BEFORE,BALANCE_AFTER,RETURN\n";
  csvFile.flush();

  std::string logFileName = "blackbird_log_" + currDateTime + ".log";
  std::ofstream logFile;
  logFile.open(logFileName.c_str(), std::ofstream::trunc);
  logFile.imbue(mylocale);
  logFile.precision(2);
  logFile << std::fixed;
  params.logFile = &logFile;
  logFile << "--------------------------------------------" << std::endl;
  logFile << "|   Blackbird Bitcoin Arbitrage Log File   |" << std::endl;
  logFile << "--------------------------------------------\n" << std::endl;
  logFile << "Blackbird started on " << printDateTime() << "\n" << std::endl;


  if (params.useDatabase) {
    logFile << "Connected to database \'" << params.dbName << "\'\n" << std::endl;
  }

  if (params.demoMode) {
    logFile << "Demo mode: trades won't be generated\n" << std::endl;
  }

  std::cout << "Log file generated: " << logFileName << "\nBlackbird is running... (pid " << getpid() << ")\n" << std::endl;

  std::vector<Bitcoin*> btcVec;
  int num_exchange = params.nbExch();

  for (int i = 0; i < num_exchange; ++i) {
    btcVec.push_back(new Bitcoin(i, params.exchName[i], params.fees[i], params.canShort[i], params.isImplemented[i]));
  }
  curl_global_init(CURL_GLOBAL_ALL);
  params.curl = curl_easy_init();

  logFile << "[ Targets ]" << std::endl;
  logFile << "   Spread Entry:  " << params.spreadEntry * 100.0 << "%" << std::endl;
  logFile << "   Spread Target: " << params.spreadTarget * 100.0  << "%" << std::endl;
  if (params.spreadEntry <= 0.0) {
    logFile << "   WARNING: Spread Entry should be positive" << std::endl;
  }
  if (params.spreadTarget <= 0.0) {
    logFile << "   WARNING: Spread Target should be positive" << std::endl;
  }
  logFile << std::endl;
  // store current balances
  logFile << "[ Current balances ]" << std::endl;
  double* balanceUsd = (double*)malloc(sizeof(double) * num_exchange);
  double* balanceBtc = (double*)malloc(sizeof(double) * num_exchange);
  for (int i = 0; i < num_exchange; ++i) {
    if (params.demoMode) {
      balanceUsd[i] = 0.0;
      balanceBtc[i] = 0.0;
    } else {
      balanceUsd[i] = getAvail[i](params, "usd");
      balanceBtc[i] = getAvail[i](params, "btc");
    }
  }
  // contains balances after a completed trade
  double* newBalUsd = (double*)malloc(sizeof(double) * num_exchange);
  double* newBalBtc = (double*)malloc(sizeof(double) * num_exchange);
  memset(newBalUsd, 0.0, sizeof(double) * num_exchange);
  memset(newBalBtc, 0.0, sizeof(double) * num_exchange);

  for (int i = 0; i < num_exchange; ++i) {
    logFile << "   " << params.exchName[i] << ":\t";
    if (params.demoMode) {
      logFile << "n/a (demo mode)" << std::endl;
    } else if (!params.isImplemented[i]) {
      logFile << "n/a (API not implemented)" << std::endl;
    } else { 
      logFile << balanceUsd[i] << " USD\t" << std::setprecision(6) << balanceBtc[i]  << std::setprecision(2) << " BTC" << std::endl;
    }
    if (balanceBtc[i] > 0.0300) {
      logFile << "ERROR: All BTC accounts must be empty before starting Blackbird" << std::endl;
      return -1;
    }
  }
  logFile << std::endl;
  logFile << "[ Cash exposure ]" << std::endl;
  if (params.demoMode) {
    logFile << "   No cash - Demo mode" << std::endl;
  } else {
    if (params.useFullCash) {
      logFile << "   FULL cash used!" << std::endl;
    } else {
      logFile << "   TEST cash used\n   Value: $" << params.cashForTesting << std::endl;
    }
  }
  logFile << std::endl;

  time_t rawtime;
  rawtime = time(NULL);
  struct tm* timeinfo;
  timeinfo = localtime(&rawtime);
  // wait the next gapSec seconds before starting
  time(&rawtime);
  timeinfo = localtime(&rawtime);
  while ((int)timeinfo->tm_sec % params.gapSec != 0) {
    sleep(0.01);
    time(&rawtime);
    timeinfo = localtime(&rawtime);
  }
  // main loop
  if (!params.verbose) {
    logFile << "Running..." << std::endl;
  }
  bool inMarket = false;
  int resultId = 0;
  Result res;
  res.clear();
  unsigned currIteration = 0;
  bool stillRunning = true;
  time_t currTime;
  time_t diffTime;
  while (stillRunning) {

    currTime = mktime(timeinfo);
    time(&rawtime);
    diffTime = difftime(rawtime, currTime);
    // check if we are already too late
    if (diffTime > 0) {
      logFile << "WARNING: " << diffTime << " second(s) too late at " << printDateTime(currTime) << std::endl;
      timeinfo->tm_sec = timeinfo->tm_sec + (ceil(diffTime / params.gapSec) + 1) * params.gapSec;
      currTime = mktime(timeinfo);
      sleep(params.gapSec - (diffTime % params.gapSec));
      logFile << std::endl;
    }
    else if (diffTime < 0) {
      sleep(-difftime(rawtime, currTime));  // sleep until the next iteration
    }
    if (params.verbose) {
      if (!inMarket) {
        logFile << "[ " << printDateTime(currTime) << " ]" << std::endl;
      } else {
        logFile << "[ " << printDateTime(currTime) << " IN MARKET: Long " << res.exchNameLong << " / Short " << res.exchNameShort << " ]" << std::endl;
      }
    }
    for (int e = 0; e < num_exchange; ++e) {
      double bid = getQuote[e](params, true);
      double ask = getQuote[e](params, false);
      if (params.useDatabase) {
        addBidAskToDb(dbTableName[e], printDateTimeDb(currTime), bid, ask, params);
      }
      if (bid == 0.0) {
        logFile << "   WARNING: " << params.exchName[e] << " bid is null, use previous one" << std::endl;
      }
      if (ask == 0.0) {
        logFile << "   WARNING: " << params.exchName[e] << " ask is null, use previous one" << std::endl;
      }
      if (params.verbose) {
        logFile << "   " << params.exchName[e] << ": \t" << bid << " / " << ask << std::endl;
      }
      btcVec[e]->updateData(bid, ask, 0.0);
      curl_easy_reset(params.curl);
    }
    if (params.verbose) {
      logFile << "   ----------------------------" << std::endl;
    }

    // compute entry point
    if (!inMarket) {
      for (int i = 0; i < num_exchange; ++i) {
        for (int j = 0; j < num_exchange; ++j) {
          if (i != j) {
            if (checkEntry(btcVec[i], btcVec[j], res, params)) {
              // entry opportunity found
              res.exposure = std::min(balanceUsd[res.idExchLong], balanceUsd[res.idExchShort]);
              if (params.demoMode) {
                logFile << "INFO: Opportunity found but no trade will be generated (Demo mode)" << std::endl;
                break;
              }
              if (res.exposure == 0.0) {
                logFile << "WARNING: Opportunity found but no cash available. Trade canceled" << std::endl;
                break;
              }
              if (params.useFullCash == false && res.exposure <= params.cashForTesting) {
                logFile << "WARNING: Opportunity found but no enough cash. Need more than TEST cash (min. $" << params.cashForTesting << "). Trade canceled" << std::endl;
                break;
              }
              if (params.useFullCash) {
                res.exposure -= params.untouchedCash * res.exposure;  // leave untouchedCash
                if (res.exposure > params.maxExposure) {
                  logFile << "WARNING: Opportunity found but exposure ($" << res.exposure << ") above the limit" << std::endl;
                  logFile << "         Max exposure will be used instead ($" << params.maxExposure << ")" << std::endl;
                  res.exposure = params.maxExposure;
                }
              } else {
                res.exposure = params.cashForTesting;  // use test money
              }
              double volumeLong = res.exposure / btcVec[res.idExchLong]->getAsk();
              double volumeShort = res.exposure / btcVec[res.idExchShort]->getBid();
              double limPriceLong = getLimitPrice[res.idExchLong](params, volumeLong, false);
              double limPriceShort = getLimitPrice[res.idExchShort](params, volumeShort, true);
              if (limPriceLong - res.priceLongIn > params.priceDeltaLim || res.priceShortIn - limPriceShort > params.priceDeltaLim) {
                logFile << "WARNING: Opportunity found but not enough liquidity. Trade canceled" << std::endl;
                logFile << "         Target long price:  " << res.priceLongIn << ", Real long price:  " << limPriceLong << std::endl;
                logFile << "         Target short price: " << res.priceShortIn << ", Real short price: " << limPriceShort << std::endl;
                res.trailing[res.idExchLong][res.idExchShort] = -1.0;
                break;
              }
              inMarket = true;
              resultId++;
              // update result
              res.id = resultId;
              res.entryTime = currTime;
              res.priceLongIn = limPriceLong;
              res.priceShortIn = limPriceShort;
              res.printEntry(*params.logFile);
              res.maxSpread[res.idExchLong][res.idExchShort] = -1.0;
              res.minSpread[res.idExchLong][res.idExchShort] = 1.0;
              res.trailing[res.idExchLong][res.idExchShort] = 1.0;
              int longOrderId = 0;
              int shortOrderId = 0;
              // send orders
              longOrderId = sendOrder[res.idExchLong](params, "buy", volumeLong, btcVec[res.idExchLong]->getAsk());
              shortOrderId = sendOrder[res.idExchShort](params, "sell", volumeShort, btcVec[res.idExchShort]->getBid());
              // wait for the orders to be filled
              logFile << "Waiting for the two orders to be filled..." << std::endl;
              sleep(3.0);
              while (!isOrderComplete[res.idExchLong](params, longOrderId) || !isOrderComplete[res.idExchShort](params, shortOrderId)) {
                sleep(3.0);
              }
              logFile << "Done" << std::endl;
              longOrderId = 0;
              shortOrderId = 0;
              break;
            }
          }
        }
        if (inMarket) {
          break;
        }
      }
      if (params.verbose) {
        logFile << std::endl;
      }
    }
    // in market, looking to exit
    else if (inMarket) {
      if (checkExit(btcVec[res.idExchLong], btcVec[res.idExchShort], res, params, currTime)) {
        // exit opportunity found
        // check current exposure
        double* btcUsed = (double*)malloc(sizeof(double) * num_exchange);
        for (int i = 0; i < num_exchange; ++i) {
          btcUsed[i] = getActivePos[i](params);
        }
        double volumeLong = btcUsed[res.idExchLong];
        double volumeShort = btcUsed[res.idExchShort];
        double limPriceLong = getLimitPrice[res.idExchLong](params, volumeLong, true);
        double limPriceShort = getLimitPrice[res.idExchShort](params, volumeShort, false);

        if (res.priceLongOut - limPriceLong > params.priceDeltaLim || limPriceShort - res.priceShortOut > params.priceDeltaLim) {
          logFile << "WARNING: Opportunity found but not enough liquidity. Trade canceled" << std::endl;
          logFile << "         Target long price:  " << res.priceLongOut << ", Real long price:  " << limPriceLong << std::endl;
          logFile << "         Target short price: " << res.priceShortOut << ", Real short price: " << limPriceShort << std::endl;
          res.trailing[res.idExchLong][res.idExchShort] = 1.0;
        } else {
          res.exitTime = currTime;
          res.priceLongOut = limPriceLong;
          res.priceShortOut = limPriceShort;
          res.printExit(*params.logFile);
          int longOrderId = 0;
          int shortOrderId = 0;
          logFile << std::setprecision(6) << "BTC exposure on " << params.exchName[res.idExchLong] << ": " << volumeLong << std::setprecision(2) << std::endl;
          logFile << std::setprecision(6) << "BTC exposure on " << params.exchName[res.idExchShort] << ": " << volumeShort << std::setprecision(2) << std::endl;
          logFile << std::endl;
          // send orders
          longOrderId = sendOrder[res.idExchLong](params, "sell", fabs(btcUsed[res.idExchLong]), btcVec[res.idExchLong]->getBid());
          shortOrderId = sendOrder[res.idExchShort](params, "buy", fabs(btcUsed[res.idExchShort]), btcVec[res.idExchShort]->getAsk());
          // wait for the orders to be filled
          logFile << "Waiting for the two orders to be filled..." << std::endl;
          sleep(3.0);
          while (!isOrderComplete[res.idExchLong](params, longOrderId) || !isOrderComplete[res.idExchShort](params, shortOrderId)) {
            sleep(3.0);
          }
          logFile << "Done\n" << std::endl;
          longOrderId = 0;
          shortOrderId = 0;
          inMarket = false;
          // new balances
          for (int i = 0; i < num_exchange; ++i) {
            newBalUsd[i] = getAvail[i](params, "usd");
            newBalBtc[i] = getAvail[i](params, "btc");
          }
          for (int i = 0; i < num_exchange; ++i) {
            logFile << "New balance on " << params.exchName[i] << ":  \t";
            logFile << newBalUsd[i] << " USD (perf $" << newBalUsd[i] - balanceUsd[i] << "), ";
            logFile << std::setprecision(6) << newBalBtc[i]  << std::setprecision(2) << " BTC" << std::endl;
          }
          logFile << std::endl;
          // update res with total balance
          for (int i = 0; i < num_exchange; ++i) {
            res.befBalUsd += balanceUsd[i];
            res.aftBalUsd += newBalUsd[i];
          }
          // update current balances with new values
          for (int i = 0; i < num_exchange; ++i) {
            balanceUsd[i] = newBalUsd[i];
            balanceBtc[i] = newBalBtc[i];
          }
          logFile << "ACTUAL PERFORMANCE: " << "$" << res.aftBalUsd - res.befBalUsd << " (" << res.totPerf() * 100.0 << "%)\n" << std::endl;
          csvFile << res.id << "," << res.exchNameLong << "," << res.exchNameShort << "," << printDateTimeCsv(res.entryTime) << "," << printDateTimeCsv(res.exitTime);
          csvFile << "," << res.getLength() << "," << res.exposure * 2.0 << "," << res.befBalUsd << "," << res.aftBalUsd << "," << res.totPerf() << "\n";
          csvFile.flush();
          if (params.sendEmail) {
            sendEmail(res, params);
            logFile << "Email sent" << std::endl;
          }
          res.clear();
          std::ifstream infile("stop_after_exit");
          if (infile.good()) {
            logFile << "Exit after last trade (file stop_after_exit found)" << std::endl;
            stillRunning = false;
          }
        }
      }
      if (params.verbose) {
        logFile << std::endl;
      }
    }
    timeinfo->tm_sec = timeinfo->tm_sec + params.gapSec;
    currIteration++;
    if (currIteration >= params.debugMaxIteration) {
      logFile << "Max iteration reached (" << params.debugMaxIteration << ")" <<std::endl;
      stillRunning = false;
    }
  }
  for (int i = 0; i < num_exchange; ++i) {
    delete(btcVec[i]);
  }
  curl_easy_cleanup(params.curl);
  curl_global_cleanup();
  if (params.useDatabase) {
    mysql_close(params.dbConn);
  }
  csvFile.close();
  logFile.close();

  return 0;
}
Exemple #10
0
vsx_module_param_list::~vsx_module_param_list()
{
  for (unsigned long i = 0; i < id_vec.size(); ++i)
  {
    switch ( id_vec[i]->type )
    {
      case VSX_MODULE_PARAM_ID_INT:
        delete ((vsx_module_param_int*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_RENDER:
        delete ((vsx_module_param_render*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_FLOAT3:
        delete ((vsx_module_param_float3*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_DOUBLE:
        delete ((vsx_module_param_double*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_STRING:
        delete ((vsx_module_param_string*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_TEXTURE:
        delete ((vsx_module_param_texture*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_FLOAT:
        delete ((vsx_module_param_float*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_FLOAT4:
        delete ((vsx_module_param_float4*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_MATRIX:
        delete ((vsx_module_param_matrix*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_MESH:
        delete ((vsx_module_param_mesh*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_BITMAP:
        delete ((vsx_module_param_bitmap*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_PARTICLESYSTEM:
        delete ((vsx_module_param_particlesystem*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_FLOAT_ARRAY:
        delete ((vsx_module_param_float_array*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_FLOAT3_ARRAY:
        delete ((vsx_module_param_float3_array*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_QUATERNION_ARRAY:
        delete ((vsx_module_param_quaternion_array*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_SEQUENCE:
        delete ((vsx_module_param_sequence*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_SEGMENT_MESH:
        delete ((vsx_module_param_segment_mesh*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_ABSTRACT:
        delete ((vsx_module_param_abstract*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_QUATERNION:
        delete ((vsx_module_param_quaternion*)id_vec[i]);
        break;


      case VSX_MODULE_PARAM_ID_RESOURCE:
        delete ((vsx_module_param_resource*)id_vec[i]);
        break;
    }
  }  
}
Exemple #11
0
QTCEXPORT(void,qtc_QTextCharFormat_finalizer)(void* x0) {
  delete ((QTextCharFormat*)x0);
}
Exemple #12
0
GlutDrawManager::
~GlutDrawManager(
){

	delete(m_drawer);
}
Exemple #13
0
void jsonnet_internal_free_vm(struct JsonnetVm *x) {
    delete(x);
}
extern "C" void AL_FUNCTION deleteALEntry( hALEntry entry )
{
    AL_ASSERT_OBJECT( entry, ALEntry, "deleteALEntry" );
    delete (ALEntry *) entry;
}
U_CDECL_BEGIN

static void U_CALLCONV deleteNorm2AllModes(void *allModes) {
    delete (Norm2AllModes *)allModes;
}
void profortosi_progress_1_1::back()
{
	delete(this);
}
Exemple #17
0
void NS_DestroyPluginInstance(nsPluginInstanceBase * aPlugin)
{
  if(aPlugin)
    delete (nsPluginInstance *)aPlugin;
}
Exemple #18
0
int exec_cmd(int under_glob, int under_until)
	{
	register int status;
	register char *p;
	int n;

	if((status = getrange()) <= ERROR)
		return( status );
	status = ERROR9;

	switch( *lp++ ) {

	case 'i':
		laddr2 = prevln(laddr2);

	case 'a':
		status = append(laddr2, under_glob);
		break;

	case 'b':
			if(!under_glob  &&  !under_until)
				status = branch();
		break;

	case 'c':
		if((status = delete(laddr1, laddr2, SAVE)) == OK)
			status = append(prevln(laddr1), under_glob);
		break;

	case 'd':
		if((status = delete(laddr1, laddr2, SAVE)) == OK && nextln(curln) != 0)
			curln = nextln(curln);
		break;

	case 'e':
		if(lastln  &&  dirty  &&  *lp != 'e') {
			status = ERROR4;
			break;
			}

		if(*lp == 'e')
			++lp;

		if(nladdrs == 0  &&  !under_glob  &&  !under_until  &&
			(status = getfn()) == OK) {
			set_fn(curfile, lp);
			if(lastln != 0)
				delete(1, lastln, NOSAVE);
			num_delete_lines = 0;
			if((status = _read( lp, 0, 0)) == OK) {
				dirty = 0;
				if(lastln)
					curln = 1;
				}
			}
		lp = "\n";
		break;

	case 'f':
		if(nladdrs == 0  &&  (status = getfn()) == OK) {
			set_fn(curfile, lp);
			putmsg(curfile);
			lp = "\n";
			}
		change_state(CMD);
		break;

	case 'g':
		if(!under_glob) {
			if(*lp == '^') {
				++lp;
				n = 0;
				}
			else
				n = 1;
			status = exec_glob(n, under_until);
			}
		break;

	case 'h':
		n = getint();
#ifndef __STDC__
		while(n--)
			for(n1 = 0; n1 < 10; ++n1)
				time_slice();
#endif
		status = OK;
		break;

	case 'j':
		status = join(laddr2);
		break;

	case 'k':
		if((status = get_laddr_expr(&n)) == OK)
			status = kopy(n);
		break;

	case 'l':
		if(nladdrs == 0)
			status = learn();
		break;

	case 'm':
		if((status = get_laddr_expr(&n)) == OK)
			status = move(n);
		break;

	case 'o':
		status = option();
		break;

	case 'p':
	case 'P':
		status = prnt(laddr1, laddr2);
		break;

	case 'q':
		if(nladdrs==0 && !under_glob) {
			if((*lp=='\n' && !dirty) || *lp=='q'  ||  lastln == 0)
				status = EOF;
			else
				status = ERROR4;
		}
		break;

	case 'r':
		if(!under_glob  &&  !under_until  &&  (status = getfn()) == OK)
			status = _read(lp, laddr2, 0);
		lp = "\n";
		break;

	case 's':
		n = getint(); /* read occurance if present */
		if((status=getpat()) == OK  &&  (status=getsubst_str(tbuff)) == OK)
			status = substitute(tbuff, under_glob, n);
		break;

	case 't':
	case 'T':
		if(nladdrs == 0)
			status = translate(*(lp - 1) == 't');
		break;

	case 'u':
		status = until(laddr1, laddr2, under_glob);
		break;

	case 'v':
		if(nladdrs <= 1)
			status = view(laddr1);
		break;

	case 'w':
		n = 0;
		if(*lp == 'w') {
			n |= 2;
			++lp;
			}
		if(*lp == 'a') {
			n |= 1;
			++lp;
			}

		if((status = getfn()) == OK) {
			if(nladdrs == 0) {
				if(curfile[0] == '\0')
					set_fn(curfile, lp);
				else {
					if((n & 2) == 0  &&  strcmp(curfile, lp) != 0) {
						for(p = lp ; *p ; ++p)
							if(*p == '$')
								goto ok;
						puterr(-19);
						lp = "\n";
						break;
						}
					}
				ok:
				if((status = _write(lp, 1, lastln, n & 1, 0)) == OK)
					dirty = 0;
				}
			} else {
				status = _write(lp, laddr1, laddr2, n & 1, 0);
			}
		lp = "\n";
		break;

    case 'x':
		if(!under_glob  &&  !under_until  &&  (status = getfn()) == OK)
			if(nladdrs == 0)
				status = exec_file(lp, under_glob, under_until);
		lp = "\n";
		break;

	case 'y':
		status = yut();
		break;

	case 'z':
		status = zap();
		break;

	case '\n':
		--lp; /* put back newline for main */
		if(laddr2 < 0  ||  laddr2 > lastln)
			status = lastln ? ERROR5 : OK;
		else {
			curln = laddr2;
			status = OK;
			}
		break;

	case ' ':
	case '\t':
	case CMD_CHAR:
		status = OK;
		break;

	case '=':
		dtoc(rbuff, laddr2);
		if(under_glob)
			prnt_screen(rbuff, 1);
		else
			putmsg(rbuff);
		status = OK;
		break;

	case '"':
		lp = "\n";	/* Ignore rest of line */
		status = OK;
		break;

	case '!':
		if(escape_char == 0  ||  restrict_flag) {
			putmsg("Escape from ED inhibited");
			status = NOTHING;
			}
		else
			status = exec_sys_cmd(under_glob, under_until);
		break;

	default:
		status = ERROR2;
		}
	return(status);
	}
Exemple #19
0
void Harmonizer2::cleanup(LV2_Handle instance)
{
    delete ((Harmonizer2 *) instance);
}
Exemple #20
0
void PacketClean::Proc(Packet *pkt){
//	cout << "Packet Clean-----------------------" << endl;
	struct timeval	packet_timestamp = pkt->GetTimestamp();

	if(savemode == PACKET){
		delete(pkt);
	}else if(savemode == STREAM){
		//if packet has no parent stream, delete it
		if(pkt->GetStream() == NULL){
			delete(pkt);
		}
	}

	//Stream End
	if(!end_stream_list.empty()){
//	cout << "Stream Endddddddd-----------------------" << endl;
//			cout << "end_stream_list size is :" << end_stream_list.size() << endl;
		for(list<Stream *>::iterator it=end_stream_list.begin(); it != end_stream_list.end(); it++){
				delete(*it);
		//	}
		}
		end_stream_list.clear();
	}


		//Gabage collect is enough 1 sec. each.
		if(packet_timestamp.tv_sec - last_gc_time.tv_sec >= 1){


			//Check all stream for timeout.
			for(list<Stream *>::iterator it=stream_pool->GetStreamFirstIt(); it != stream_pool->GetStreamLastIt(); it++){
//				cout << "Stream timeout-----------------------" << endl;
//				cout << "packet timestamp sec: " << packet_timestamp.tv_sec << endl;
//				cout << "GetLastUpdatedTime: " << (*it)->GetLastUpdatedTime().tv_sec  << endl;
//				cout << "Division: " << packet_timestamp.tv_sec - (*it)->GetLastUpdatedTime().tv_sec  << endl;
//				cout << "gc_removetime: " << gc_remove_time << endl;
//				cout << atoi(config->get("gc_remove_time").c_str()) << endl;
				if( packet_timestamp.tv_sec - (*it)->GetLastUpdatedTime().tv_sec >= atoi(config->get("gc_remove_time").c_str()) ){
					list<Stream *>::iterator it2;
					it2 = --it;
					++it;
					if(it != stream_pool->GetStreamLastIt()){
						delete *it;
					}
					it = it2;
				}
			}

			//Check all tcpconn for timeout.
			for(multimap<u_int, TcpConn*>::iterator it=tcp_conn_pool->GetTcpConnFirstIt(); it != tcp_conn_pool->GetTcpConnLastIt(); ++it){
//				cout << "TCP connection timeout-----------------------" << endl;
				if( packet_timestamp.tv_sec - (it->second)->GetLastUpdatedTime().tv_sec >=  atoi(config->get("gc_remove_time").c_str()) ){
					multimap<u_int, TcpConn*>::iterator it2;
						it2 = --it;
						++it;
					if(it != tcp_conn_pool->GetTcpConnLastIt()){
				//cout << "TcpConn removing!!"<< endl;
						delete it->second;
					}
					it = it2;
				}
			}

			last_gc_time.tv_sec = packet_timestamp.tv_sec;
		}
//		cout << "stream num :"<<stream_pool.GetSize()<< endl;
}
Exemple #21
0
DataHandler::~DataHandler() {
    delete(this->logger);
}
DLL_EXPORT void DestroyClient(void *client) {
    if (client)
        delete (CConceptClient *)client;
}
 // destroy existing segments
 foreach(MemorySegment *seg, m_regions) {
     delete(seg);
 }
Exemple #24
0
Mud::~Mud()
{
    Logger::log(LogLevel::Global, "Freeing memory occupied by players...");
    for (auto iterator : Mud::instance().mudPlayers)
    {
        delete (iterator);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by mobiles...");
    for (auto iterator : Mud::instance().mudMobiles)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by items...");
    for (auto iterator : Mud::instance().mudItems)
    {
        delete (iterator);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by rooms...");
    for (auto iterator : Mud::instance().mudRooms)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by areas...");
    for (auto iterator : Mud::instance().mudAreas)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by writings...");
    for (auto iterator : Mud::instance().mudWritings)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by corpses...");
    for (auto iterator : Mud::instance().mudCorpses)
    {
        delete (iterator);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by models...");
    for (auto iterator : Mud::instance().mudModels)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by races...");
    for (auto iterator : Mud::instance().mudRaces)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by liquids...");
    for (auto iterator : Mud::instance().mudLiquids)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by professions...");
    for (auto iterator : Mud::instance().mudProfessions)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by productions...");
    for (auto iterator : Mud::instance().mudProductions)
    {
        delete (iterator.second);
    }
    Logger::log(LogLevel::Global, "Freeing memory occupied by materials...");
    for (auto iterator : Mud::instance().mudMaterials)
    {
        delete (iterator.second);
    }
}
Exemple #25
0
/*!
  Destroys the Shift-JIS codec.
*/
QSjisCodec::~QSjisCodec()
{
    delete (QJpUnicodeConv*)conv;
    conv = 0;
}
Exemple #26
0
void QMenuBar_Destroy(QMenuBarH handle)
{
	delete (QMenuBar *)handle;
}
Exemple #27
0
void CMac::ClearLogins() { 
	list<login*>::iterator il; for(il=llStart.begin(); il!=llStart.end(); ++il)
		delete (*il);
	llStart.clear(); }
// destroy
void DestroyModule(void* pModule) 
{
	// cast is important to call the good destructor
	delete ((TemplateModule*)pModule);
}
Exemple #29
0
XDL_TileEngine::~XDL_TileEngine(void)
{
	delete(_renderer);
}
Exemple #30
0
// Remove all items from the output streamer list;
void EvtCollectionStream::clearItems()     {
  for ( Items::iterator i = m_itemList.begin(); i != m_itemList.end(); i++ )    {
    delete (*i);
  }
  m_itemList.erase(m_itemList.begin(), m_itemList.end());
}