void MarketFileSource::retrieveRecord(){ if (!_enabled) return; AbstractFileSource::retrieveRecord(); CSVDatabase db; readCSV(_inFile, db); int numOfRows=db.size(); int numOfCols=db.at(0).size(); RecordHelper::MarketMap marketMap; for (int j=1;j<numOfCols;j++) { String marketStr = db.at(0).at(j); enums::CurrencyEnum CurrencyEnum = EnumHelper::getCcyEnum(marketStr); Market* market = new Market(); for (int i=0;i<numOfRows;i++){ String fieldName=db.at(i).at(0); String fieldVal=db.at(i).at(j); updateMarketObjectField(fieldName, fieldVal, market); } market->display(); marketMap.insert(std::make_pair(CurrencyEnum,*market)); } RecordHelper::getInstance()->setMarketMap(marketMap); _inFile.close(); }
string Human::getTakeChoice(Market & market) { bool buggedcase = true; bool invalidchoice = true; do { bool invalidchar; do { cout<<endl << "Please select the cards that you would like to take:"<< endl; market.printCards(); if (buggedcase) cin.ignore(); getline(cin, choice); cout << "\033[2J\033[1;1H" << endl; choice.erase(std::remove(choice.begin(), choice.end(), ' '), choice.end()); cout << "Your choice was: " << choice << endl; invalidchar = isInvalidChar(choice); if (invalidchar) { buggedcase = false; cout << "You entered an invalid character. Please try again." << endl;; }//end if } while (invalidchar); invalidchoice = isInvalidChoice(choice, market.getSize()); if (invalidchoice) { buggedcase = false; cout << "You entered an invalid choice. Please try again." << endl; }//end if } while(invalidchoice); return choice; }
int main() { // randomData(false, 3, 5, 10000); return 0; freopen("in", "r", stdin); // Fisher ArrowDebreu // EdmondsKarp ISAP SAP Market *market = new Fisher((MaxFlow *)new EdmondsKarp()); for(int cas=1; market->read(); ++cas) { printf("cas: %d\n", cas); market->solve(); } return 0; }
void DepositFileSource::insertRateIntoMap(std::string tenorStr, double liborRate, Market market, map<long, double>* depositRateMap, map<long, double>* overnightRateMap){ date startDate = dateUtil::dayRollAdjust(dateUtil::getToday(),enums::Following,market.getMarketEnum()); char tenorUnit = *tenorStr.rbegin(); int tenorNum = std::stoi(tenorStr.substr(0,tenorStr.size()-1)); // 2 if (tenorUnit != 'D') startDate = dateUtil::getBizDateOffSet(startDate,market.getBusinessDaysAfterSpot(enums::SWAP),market.getMarketEnum()); // day after spot adjust long JDN = dateUtil::getEndDate(startDate,tenorNum, market.getDayRollCashConvention(), market.getMarketEnum(), dateUtil::getDateUnit(tenorUnit)).getJudianDayNumber(); if (tenorUnit == 'D'){ overnightRateMap->insert(pair<long, double>(tenorNum, liborRate)); cout << market.getNameString()<< " -> tenor[" << tenorStr <<"], accrual start["<<startDate.toString()<<"], duration [" <<tenorNum <<"], deposit rate["<< liborRate << "]"<<endl; }else{ date accrualEndDate(JDN); depositRateMap->insert(pair<long, double>(JDN, liborRate)); cout << market.getNameString()<< " -> tenor[" << tenorStr<<"], accrual start["<<startDate.toString()<<"], accrual end[" <<accrualEndDate.toString() <<"], deposit rate["<< liborRate << "]"<<endl; } }
RoundVector Actor::marginalRevenue(const RoundVector& prices, const RoundVector& quantity, const Market& market, const RoundVector& production) const { RoundVector mr; for (int r = 0; r <= NumRounds; r++) { mr(r) = prices(r) + quantity(r) * market.dPrice(r, production(r)); } return mr; }
/* * buy function * takes Market reference, stock, date, and quantity * returns true or false depending if conditions meet to buy */ bool Player::buy(Market &m, string stock, long date, long quantity) { bool result=true; double stockprice = m.get_price(stock,date)*quantity; if (stockprice > 0 && stockprice <= cash) { stocks[stock]+=quantity; cash -= stockprice; } else result=false; return result; }
Swaption::Swaption(Market market,PayReceive PayReceiveInd, int expiryInMonth, double strikeInBps, int tenorInMonth){ date swapStartDate = dateUtil::getEndDate(dateUtil::getToday(),expiryInMonth,enums::Mfollowing, market.getCurrencyEnum(), dateUtil::MONTH); double notional=1000000; double couponRate=0.03; int paymentFreqFixLeg=2; int paymentFreqFloatingLeg=4; bool rollAccuralDates=true; DiscountCurve* dc = MarketData::getInstance()->getSwapDiscountCurve(market.getCurrencyEnum()); SwaptionVolCube* vc = MarketData::getInstance()->getSwaptionVolCube(market.getCurrencyEnum()); //Swap* underlyingSwap= new Swap(swapStartDate, tenorInMonth, notional, couponRate, dc, market, paymentFreqFixLeg, paymentFreqFloatingLeg, rollAccuralDates); //BaseSwaption(market, PayReceiveInd, expiryInMonth, strikeInBps, vc, dc, underlyingSwap); }
void DB::loadOrders() { mongo::BSONObj o_max = getInstance().findOne("btct.orders", mongo::Query().sort("_id", -1)); mongo::BSONObj t_max = getInstance().findOne("btct.transactions", mongo::Query().sort("_id", -1)); uint64_t o_next_id = o_max.getField("_id").ok()?o_max.getField("_id").Long():10000; if(o_next_id < 10000) { o_next_id = 10000; } uint64_t t_next_id = t_max.getField("_id").ok()?t_max.getField("_id").Long():1; if(t_next_id <= 1){ t_next_id = 1; } Order::next_id = o_next_id + 1; Transaction::next_id = t_next_id + 1; std::auto_ptr<mongo::DBClientCursor> cursor = getInstance().query("btct.orders", QUERY("qty" << mongo::GT << 0)); int order_count = 0; printf("Loading orders...\n"); while (cursor->more()) { mongo::BSONObj p = cursor->next(); Market *market = Market::markets[p.getIntField("market_id")]; Order *o = new Order( market, (const uint32_t) p.getIntField("account_id"), (const order_type_t) p.getBoolField("direction"), (const uint64_t) p.getField("qty").Long(), (const uint64_t) p.getField("orig_qty").Long(), (const uint64_t) p.getField("price").Long(), (const uint64_t) p.getField("_id").Long(), (const uint32_t) p.getIntField("timestamp"), (const order_status_t) p.getIntField("status")); market->addOrder(o); order_count++; } printf("Loaded %u orders\n", order_count); printf("Biggest order number: %llu\n", o_next_id); }
/* * sell function * takes Market reference, stock, date, and quantity * returns true or false depending if conditions meet to sell */ bool Player::sell(Market &m, string stock, long date, long quantity) { bool result = true; double stockprice = m.get_price(stock,date)*quantity; auto mark = stocks.find(stock); if (mark != stocks.end()) { if (stocks[stock] >= quantity && stockprice > 0) { cash +=stockprice; stocks[stock]-=quantity; } else result=false; } else result=false; return result; }
Swap::Swap(date tradeDate, int tenorNumOfMonths, double notional, double couponRate, DiscountCurve* yc, Market fixLegCurr, Market floatingLegCurr, int paymentFreqFixLeg, int paymentFreqFloatingLeg, bool rollAccuralDates) { setTradeDate(tradeDate); setMaturityDate(dateUtil::getEndDate(tradeDate,tenorNumOfMonths,fixLegCurr.getDayRollSwapConvention(),fixLegCurr.getMarketEnum(),dateUtil::MONTH)); BuilderCashFlowLeg* fixLegs = new BuilderCashFlowLeg(enums::SWAP,tradeDate, tenorNumOfMonths,couponRate,notional, paymentFreqFixLeg, fixLegCurr.getMarketEnum()); BuilderCashFlowLeg* floatLegs= new BuilderCashFlowLeg(enums::SWAP,tradeDate, tenorNumOfMonths,yc,notional, paymentFreqFloatingLeg, floatingLegCurr.getMarketEnum()); _fixCashflowLeg=fixLegs->getCashFlowLeg(); _floatingCashflowLeg=floatLegs->getCashFlowLeg(); _yc=yc; _fixLegCurr=fixLegCurr; _floatingLegCurr=floatingLegCurr; _paymentFreqFixLeg=paymentFreqFixLeg; _paymentFreqFloatingLeg=paymentFreqFloatingLeg; _tenorNumOfMonths=tenorNumOfMonths; }
Swaption::Swaption(Market market,PayReceive PayReceiveInd, int expiryInMonth, double strikeInBps, Swap* underlyingSwap){ SwaptionVolCube* vc = MarketData::getInstance()->getSwaptionVolCube(market.getCurrencyEnum()); DiscountCurve* dc = MarketData::getInstance()->getSwapDiscountCurve(market.getCurrencyEnum()); BaseSwaption(market,PayReceiveInd, expiryInMonth, strikeInBps, vc, dc, underlyingSwap); }
Swap::Swap(date tradeDate, date maturityDate, int tenorNumOfMonths, double notional, double couponRate, DiscountCurve* yc, Market fixLegCurr, Market floatingLegCurr, int paymentFreqFixLeg, int paymentFreqFloatingLeg, bool rollAccuralDates, int buildDirection) { setTradeDate(tradeDate); setMaturityDate(maturityDate); BuilderCashFlowLeg* fixLegs = new BuilderCashFlowLeg(enums::SWAP, tradeDate, maturityDate, tenorNumOfMonths, couponRate, notional, paymentFreqFixLeg, fixLegCurr.getMarketEnum(), buildDirection); BuilderCashFlowLeg* floatLegs = new BuilderCashFlowLeg(enums::SWAP, tradeDate, maturityDate, tenorNumOfMonths, yc ,notional, paymentFreqFloatingLeg, floatingLegCurr.getMarketEnum(), buildDirection); _fixCashflowLeg=fixLegs->getCashFlowLeg(); _floatingCashflowLeg=floatLegs->getCashFlowLeg(); _yc=yc; _fixLegCurr=fixLegCurr; _floatingLegCurr=floatingLegCurr; _paymentFreqFixLeg=paymentFreqFixLeg; _paymentFreqFloatingLeg=paymentFreqFloatingLeg; }
Solution opec::solve(const Market& market) { const double Delta = 25.; const double TerminationCondition = .01; const int ReportInterval = 1000; const int TerminationQuantum = 1000; const int TerminationIterations = 100000; Solution solution(market.size()); Vector diff(market.size()); double maxDiff = 0.; int iter = 0, lastReport = 0; // 1. Initial values for (int a = 0; a < market.size(); a++) { auto& actor = *market.actors[a]; for (int r = 0; r < NumRounds; r++) { solution.quantities(a, r) = actor.reserves / NumRounds; } solution.quantities(a, NumRounds) = 0.; } auto update = [&] () { for (int r = 0; r <= NumRounds; r++) { solution.production(r) = solution.quantities.col(r).sum(); } for (int r = 0; r <= NumRounds; r++) { solution.prices(r) = market.price(r, solution.production(r)); } for (int a = 0; a < market.size(); a++) { auto& actor = *market.actors[a]; auto q = solution.quantities.row(a); double prevValue = solution.values(a); solution.values(a) = actor.value(q, solution.prices).sum(); diff(a) = solution.values(a) - prevValue; } maxDiff = std::max(maxDiff, diff.norm()); }; update(); auto initialValues = solution.values; auto report = [&] (bool output=false) { if (iter == 0 || output) { std::cout << "Iteration " << iter << ": " << solution.values.sum() << "\t(" << (100. * solution.values.sum() / initialValues.sum() - 100.) << "% improved)" << "\tChange: " << maxDiff << std::endl; } maxDiff = 0.; lastReport = iter; }; // 2. iterate to fixed point on quantity do { update(); for (int a = 0; a < market.size(); a++) { auto& actor = *market.actors[a]; auto q = solution.quantities.row(a); actor.update(solution, q); } if (iter % ReportInterval == 0) report(); // set quantity based on current prices for (int a = 0; a < market.size(); a++) { auto& actor = *market.actors[a]; auto q = solution.quantities.row(a); // this vector points in the direction of greatest profit; // this is where we want to move. we need to scale the // prices to reflect inflation. auto margin = actor.marginalRevenue(solution.prices, q, market, solution.production); margin -= actor.marginalCost(q); margin = Market::inflate(margin); RoundVector step = project(margin).normalized() * Delta; assert(feq(step.sum(), 0.)); // we're moving along a constant constraint; the net change must be zero // enforce capacity constraints...can't produce negative // or exceed capacity. if we have violated a constraint, // move to the corner case and zero out the step on that // dimension RoundVector constraints = roundOrthogonal; bool satisfied = false; while (!satisfied) { satisfied = true; for (int r = 0; r <= NumRounds; r++) { auto capacity = (r < NumRounds) ? actor.capacity : std::numeric_limits<int>::max(); auto nq = q(r) + step(r); if (nq > capacity || nq < 0.) { if (nq > capacity) q(r) = capacity; else q(r) = 0.; constraints(r) = 0.; step(r) = 0.; satisfied = false; } } // renormalize step to keep reserve constraint ... this // will naturally reduce the size of the step if we are in // a corner solution, so we don't re-scale by Delta. constraints.normalize(); step = project(step, constraints); } // make the move! q += step; actor.isConstrained(q); } } while ((++iter < TerminationIterations) && ((iter - lastReport) < TerminationQuantum || maxDiff > TerminationCondition)); report(true); verify(solution, market); return solution; }
void updateRow(std::uint64_t tag, const Market& market) { TableModel::updateRow(market.id(), tag, market); }
void removeRow(const Market& market) { TableModel::removeRow(market.id()); }