Sei sulla pagina 1di 18

1

EECS281Fall2014
Project3:StocksonStocks
onStocks
Due Thursday, November 13th at 11:55pm
Overview
In this project, you will write an electronicstockexchange market. The market offers a variety ofequities.Any
market client can place a buy or sell order on an equity to request that a transaction be executed when
matching sellers or buyersbecome available. Your program should take in buy and sellorders for avarietyof
equities as they arrive and match buyers with sellers to executetrades as quickly as possible.Inaddition,you
will have the ability to create an insider trader allowing for instantaneous trades, letting your stock exchange
makeevenmoremoneyontheside.

ProjectGoals

Usecoredatastructures:priorityqueues(std::priority_queue),hashtables
(std::unordered_map,std::unordered_set,std::unordered_multimap,
std::unordered_multiset),andbinarysearchtrees(std::map,std::set,std::multimap,
std::multiset)
BecomemoreproficientwithusingObjectOrientedProgrammingtomakebetterdesigndecisions
BecomemorefamiliarwiththeSTLandpracticetheabilitytouseiteffectively

Input
Theinputwillarrivefromstandardinput(cin),notfromanifstream.Therewillbetwoinputformats,tradelist
(TL)andpseudorandom(PR).TheformatisindicatedbythefirstlineofinputwhichwillbeeitherTLorPR
(neverboth)andappliestotheentiretyoftheinput.

ForTradeList(TL)Input:
Version102414
2014RegentsoftheUniversityofMichigan

Theinputwillcontainaseriesofordersthatwillbepresentedsuchthatorderswithlowertimestampsalways
appearfirst.Orderswillbeformattedasfollows:

TIMESTAMPCLIENT_NAMEBUY_OR_SELLEQUITY_SYMBOL$PRICE#QUANTITY

Onasingleline,withallfieldsseparatedbyoneormorespaces/tabs.Forexample:

TL
0JackBUYGOOG$100#50

Toavoidunexpectedlossesoflargeamountsofmoney,youmustcheckforinvalidinput.Specifically,youmust
checkthat:
Nonnegative,integervaluesaregivenforTIMESTAMP.
Positive,integervaluesaregivenforPRICE.
Allordersarriveintimestamporder(where0isthelowestpossibletimestampvalue).
Boththe$and#signsappearwheretheyareexpected.
Theequitynamemustcontainonlyalphanumericcharacters,underscores,periods,andbelessthanor
equalto5characters.
Theclientnamemustcontainalphanumericcharactersandunderscores.
TheBUY_OR_SELLfieldmustonlycontaineitherthestringBUYorSELL.
Notethatonceatimestampisreadonanewlineitcanbeassumedthatallthefollowingfieldswillbe
presentintheline.Youwillnotbegiveninputfileswithpartialorders.

Ifyoudetectinvalidinputatanytimeduringtheprogram,exit(1).Youdonotneedtocheckforother
kindsofinputerrorswewillnotbetestingforerrorsnotspecifiedhere.

FieldInformation:
TIMESTAMPWillbeanonnegativeintegervaluecorrespondingtotheUNIXepochtime,whereadding
1tothevaluemeansadding1second.Youshouldnottrytointerpretthistimestampintoits
correspondingdate/time,asyouwillonlyneeditforcomparison,whichcanbeconvenientlydonewith
thenormaloperators.
CLIENT_NAMEThebuyerorsellersname.Thiswillbeastringthatcontainsonlyalphanumeric
charactersand_(seestd::isalnumforadefinitionofalphanumeric).
BUY_OR_SELLThestring"BUY"orthestring"SELL"correspondingtothetypeoforder.
EQUITY_SYMBOLTheshorthandnameoftheequity.Thiswillbeastringthatcontains15characters
thatarealphanumericor_or.(examples:C,F,GM,KO,TGT,WMT,AAPL,PZZA,BRK.A,BRK.B)
PRICEThisisapositiveinteger(notzero).Ifitsabuy order,thisisthehighestpriceabuyeriswilling
topayfortheequity.Ifitsasell order,thisisthelowestpricetheselleriswillingtoselltheequityfor.
Buyersmaypaylessthantheirlimitprice,sellersmightgetmoremoneythantheminimumtheyaskfor
(seebelow).The$signwillappearintheinputbeforethisvalue.
QUANTITYApositiveintegernumberofstockstheclientwantstobuy/sell.The#signwillappearin
theinputbeforethisvalue.

Version102414
2014RegentsoftheUniversityofMichigan

Allvalidinputwillbearrangedbytimestamp(lowesttimestampfirst).Asyoureadinorders,youshouldassign
allordersauniqueIDnumber,suchthatthefirstorderyoureadgetsanIDof0,thesecondanIDof1,andso
on.TheseIDnumbersensurethatthereisonlyonepossiblematchingofbuyersandsellersbasedonarrival
timestamps.Theyarealsousefulfortrackinganddebugging.

ForPseudorandom(PR)Input:
Todeterminethetimestampofrandomlygeneratedorders,yourprogramwillmakeuseofa
GENERATOR_TIMESTAMP,whoseinitialvalueisalways0.

Youwillbegiventhefollowingintegervalues,witheachitemonitsownline:
RANDOM_SEEDThevaluetoinitializetherandomseedto.
NUMBER_OF_ORDERSThenumberoforderstogenerate.Youmayassumethatthisvaluewillbeless
thanorequalto 232 1 .
LAST_CLIENTThenameofthelastclientthatwillbetrading.Thisvaluewillbeacharacterbetween
aandz.
LAST_EQUITYTheofnameofthelastequitythatwillbetraded.Thisvaluewillbeacharacter
betweenAandZ
ARRIVAL_RATEAdoublecorrespondingtothearrivalrate,orapproximatelyoneovertheaverage
timebetweenorderarrivals.WearegoingtousethearrivalratetoapproximateaPoissonarrival
process.APoissonprocessassumesthatthetimeofthenextarrivalisindependentoftheamountof
timethathaspassedsincethepreviousarrival.WecanapproximateaPoissonprocessbyobserving
thatthetimebetweenarrivalsisexponentiallydistributed.

Thisinformationwillbeprovidedviastandardinput(cin)inexactlythisformat/arrangement,whichyoumay
assumewillalwaysbecorrectlyformatted:

PR
RANDOM_SEED:3453243
NUMBER_OF_ORDERS:20
LAST_CLIENT:b
LAST_EQUITY:C
ARRIVAL_RATE:1.8

Fortheaboveexamplefile,20totalorderswillbegenerated,withclients"C_a"and"C_b"tradingthe"E_A",
"E_B,and"E_Cequities(seebelow).

Theprocedureforgeneratingyourinputinpseudorandommodeisasfollows:
1. Include<random>inyourheader
2. Seedthetherandomnumbergeneratorwithstd::mt19937gen(RANDOM_SEED)
3. Initializeseveraldistributionsforthevariousrandomelements:
std::uniform_int_distribution<char>clients('a',LAST_CLIENT)
std::uniform_int_distribution<char>equities('A',LAST_EQUITY)
Version102414
2014RegentsoftheUniversityofMichigan

std::exponential_distribution<>arrivals(ARRIVAL_RATE)
std::bernoulli_distributionbuy_or_sell
std::uniform_int_distribution<>price(2,11)
std::uniform_int_distribution<>quantity(1,30)

4. Foreachrandomlygeneratedtradeusethefollowingpseudocodetogenerateallaspectsoftheorder:
TIMESTAMP:=GENERATOR_TIMESTAMP
GENERATOR_TIMESTAMP:=GENERATOR_TIMESTAMP+floor(arrivals(gen)+.5)
CLIENT_NAME:=string("C_")+clients(gen)
//Rangeofpossibleclientnamesisthus'C_a'to'C_z'.
BUY_OR_SELL:=(buy_or_sell(gen)?BUY:SELL)
EQUITY_SYMBOL:=string("E_")+equities(gen)
//Rangeofpossibleequitynamesisthus"E_A"to"E_Z".
PRICE:=5*price(gen)//$10$55
QUANTITY:=quantity(gen)//130

Note:Thesefieldsshouldbecomputedinexactlythisordertobeconsistentwiththeautograder.
AllvalueshavethesamemeaningasinTradeList(TL)inputs,andshouldbeusedinexactlythesameway.
IDnumbersshouldbegiveninthesamemanner,exceptnowtheycorrespondtoorderofgeneration.Ifaclient
inthegivenrangeisnotgenerated,thenitshouldnotproduceanyoutput.

Byfollowingthegivenprocedurewiththeinputabove,youshouldgeneratethesameorderlistasthefollowing
TLinput:

TL
0C_bSELLE_B$25#26
1C_bSELLE_C$25#10
1C_aSELLE_B$15#22
1C_aBUYE_B$55#7
2C_aBUYE_B$35#22
2C_bBUYE_C$25#26
2C_bBUYE_A$25#23
3C_aBUYE_C$35#21
3C_bSELLE_A$55#4
3C_bBUYE_B$30#29
3C_aBUYE_B$20#22
4C_aBUYE_B$10#21
4C_bSELLE_C$40#2
4C_bBUYE_A$50#5
4C_bSELLE_B$45#19
4C_aSELLE_C$50#26
5C_aSELLE_C$40#8
6C_bBUYE_C$40#3
Version102414
2014RegentsoftheUniversityofMichigan

6C_bSELLE_B$20#30
7C_aBUYE_C$30#11

MarketLogic
CURRENT_TIMESTAMPshouldalwaysstartat0,itisthenmaintainedthroughouttherunoftheprogram.

Yourprogrammustperformthefollowingtasks:
1. Addanyinsidersintoyourclientsdatastructuressothattheyareprintedoutusingthetransfersflagat
theendofdayevenifnotradeisperformed.(InsiderLogicisexplainedbelow).
2. Readthenextorderfrominput
3. IftheordersTIMESTAMP!=CURRENT_TIMESTAMPthen:
a. Ifthemedianoptionisspecified,printthemedianpriceofallequitiesthathavebeentraded
onatleastoncebythispointinlexicographicalorderbyEQUITY_SYMBOL(seebelow).
b. SetCURRENT_TIMESTAMPequaltotheordersTIMESTAMP.
4. Addtheorderfromstep2toyourdatastructures.
5. Processallpossibletradeswiththeinformationinyourdatastructures(matchbuyerstosellers).Ifany
orderscannotbefilled,youshouldleavetheminyourdatastructurestomatchwithfutureorders.
6. Ifthereisaninsiderfortheequitytradedthenperformthefollowingsteps:
a. Determineifabuyshouldbeperformedgiventhecurrentmarketpriceoftheequity.
i. Ifthebuyshouldbeperformed,addtheinsiderbuyertoyourdatastructures.
ii. Afteraddingthebuyer,processallpossibletrades,asinstep5.
b. Determineifasellshouldbeperformedgiventhecurrentmarketpriceoftheequity.
i. Ifthesellshouldbeperformed,addtheinsidersellertoyourdatastructures.
ii. Afteraddingtheseller,processallpossibletrades,asinstep5.
7. Repeatprevioussteps26untiltheendoftheday,definedaswhenthereisnomoreinput(andthusno
moretradestobeperformed).
8. Treattheendofdaylikethetimestamphasmovedagain,andoutputmedianinformationasnecessary.
9. Printallendofdayoutput.

OrdersandTrades
Allordersonthemarketareconsideredlimit orders.Abuylimit orderexpressestheintenttobuyatmostN
sharesofagivenstockatnomorethanDdollarspershare,whereDiscalledthelimit.Aselllimitorder
expressestheintenttosellatmostNsharesofagivenstockatnolessthanDdollarspershare.Tofacilitate
tradeexecution,anordercanbesplitandmatchedwithseveralotherordersatdifferentexecutionprices.

Orderbooksandtradeexecution
Foreachgivenequity,youshouldkeeptrackofallcurrentbuyandsellordersinadedicatedcontainerdata

Version102414
2014RegentsoftheUniversityofMichigan

structurecalledanorderbook. Atradecanbeexecutedforagivenequitywhenthebuy orderwiththe


highestlimit price(andintheeventofties,lowestIDnumber)hasabuy limit pricegreaterthanor
equaltothesell limit priceofthesell order withthelowest limit price(andintheeventofties,
lowestIDnumber).Foragivenorderbook,theorderoftradeexecutionisfullydetermined.Youmustsupport
thisordercorrectlyandensurehighspeedoftradeexecutionbyoptimizingdatastructures.

Forexample,giventhefollowingordersasinput:

0SELLER_1SELLGOOG$125#10
0SELLER_2SELLGOOG$100#30
0SELLER_3SELLGOOG$100#15
0BUYER_1BUYGOOG$200#4
0BUYER_2BUYGOOG$250#50
0SELLER_4SELLGOOG$60#20

ThefirsttradetobeexecutedwouldbeBUYER_1buying4ofSELLER_2sshares.Thisisbecauseatthis
point,theprogramhasnotreadBUYER_2sorderyet(seemarketlogicsection)andSELLER_2hasthelowest
sellprice.WhileSELLER_2andSELLER_3arebothsellingatthesameprice,SELLER_2sorderarrivedfirst,
andwillthereforehavealowerIDnumber.

Whenthatfirsttradeisexecuted,SELLER_2sordermustberevisedtoofferonly26shares(because4had
alreadybeentraded).Therevisedorderkeepstheidoftheoriginalorder.

Wheneveratradeisexecuted,thematchpriceofthetradeisthelimitpriceoftheorder(buyorsell)withthe
lowerIDnumber.Inthiscase,BUYER_1offeredtobuyfor$200andSELLER_2offeredtosellfor$100
becauseSELLER_2hasalowerIDnumber,thetradewillbeexecutedatamatch priceof$100pershare.

Commissionfeesandtradereporting
Forprovidingthismatchingservice,themarket(andthusyourprogram)alsotakesacommission feeof1%
fromeverycompletedtradefromboththebuyerandtheseller.Thecommissioninourexampleis:
(100 4)/100 = $4 fromboththebuyerandseller.

AndsoBUYER_1willpay (100 4) + 4 = $404 ,S


ELLER_2willreceive (100 4) 4 = $396 ,andTheMarket

willearnacommissionof (2 4) = $8 .Forthesecalculations,allvaluesshouldbeintegersandthereforeall

decimalswillbetruncated.Commissionsmustbecomputedexactlyasabovewhenexecutingthetradetobe
clear,donotcalculatethecombinedcommissionsofthebuyerandsellerinasinglearithmeticexpression
(suchas total_commission = match_price num_shares/100 2 ),asthismayyielddifferentresultswhen
1

Thereisaconsiderablenumberofpossibledifferentdatastructuresfortheorderbook,includingreusableSTLdata
structuresandhybrids.Werecommendcarefullyanalyzingseveralalternativesbeforecommittingtoone.Youmaywantto
experimentwithseveraldatastructures,sokeeptheinterfacesufficientlyindependentoftheimplementation.Sometimesit
maybeusefultoswitchfromonedatastructuretoanotherdynamically,butthisisnotarequirement.
Version102414
2014RegentsoftheUniversityofMichigan

truncating.Firstcalculatethecommissionasshown,thenmultiplytheresultby2instead.

CommandLineInput
Yourprogrammarketshouldtakethefollowingcasesensitivecommandlineoptions:
s,summary
Anoptionalflagthatindicatestheprogramshouldprintavarietyofsummaryinformationdescribingthe
daystrades(SeeOutputsectionbelow).
v,verbose
Anoptionalflagthatindicatestheprogramshouldprintadditionaloutputinformationwhiletradesare
beingexecuted(SeeOutputsectionbelow).
m,median
Anoptionalflagthatindicatestheprogramshouldprintthecurrentmedianmatch priceforeachequity
atthetimesspecifiedintheMarketLogicsectionabove,i.e.duringexecution.
t,transfers
Anoptionalflagthatindicatestheprogramshouldprintadditionaloutputinformationattheend of the
daytoshowthenetamountoffundstransferredbyallclients(seeOutputsectionbelow).
i,insiderEQUITY_SYMBOL
Anoptionalflagthatmayappearmorethanoncewithdifferentequitysymbolsasarguments.The
insideroptionallowsfortheprogramitselftohaveanadvantageoverotherbuyersandsellersbybeing
abletoinstantaneouslyinsertitsownbuysandsellsintotheinputqueue.Moreinformationinthe
Insiderssection.
g,tttEQUITY_SYMBOL
Anoptionalflagthatmayappearmorethanoncewithdifferentequitysymbolsasarguments.The
TimeTravelTradingoptionrequeststhat,attheendofthedaytheprogramdetermineswhatwasthe
besttimetobuy(once)andthensubsequentlysell(once)aparticularequityduringthedaytomaximize
profit.Moreinformationintheoutputsection.
h,help
Anoptionalflagthatindicatesyoushouldprintahelpmessageandthenexit,regardlessofanyother
commandlineoptions.

Ifmultipleoptionsarespecifiedthatproduceoutputattheendoftheprogram,theoutputshouldbe
printedintheorderthattheyarelistedhereinthespec(e.g.,summarybeforetransfersbefore
ttt).

Version102414
2014RegentsoftheUniversityofMichigan

Examplesoflegalcommandlines:
./market<infile.txt>outfile.txt
./marketverbosetransferssummary>outfile.txt
./marketverbosemedian>outfile.txt
./markettttGOOGiIBM
./markettransferssverbosetttGOOGtttIBMinsiderGOOG
./marketvmtiGOOGgIBMs
./markethelpt
(Notethattwillnotrun,butstillvalidinput)

Wewillnotbespecificallyerrorcheckingyourcommandlinehandling,howeverweexpectthatyour
programconformswiththedefaultbehaviorofgetopt_long.Incorrectcommandlinehandlingmaylead
toavarietyofdifficulttodiagnoseproblems.

Output
Default
Attheend of the day,afterallinputhasbeenreadandallpossibletradescompleted,thefollowingoutput
shouldalwaysbeprintedbeforeanyoptionalendofdayoutput:

EndofDay

Summary
Ifandonlyifthesummaryoptionisspecifiedonthecommandline,youshouldprintthefollowing
informationgivingasummaryofthedaystrades:

CommissionEarnings:$COMMISION_EARNINGS
TotalAmountofMoneyTransferred:$MONEY_TRANSFERRED
NumberofCompletedTrades:NUMBER_OF_COMPLETED_TRADES
NumberofSharesTraded:NUMBER_OF_SHARES_TRADED

VerboseOption
Ifandonlyiftheverboseoptionisspecifiedonthecommandline(seeabove),wheneveratradeis
completedyoushouldprint:

BUYER_NAMEpurchasedNUMBER_OF_SHARESsharesofEQUITY_SYMBOLfromSELLER_NAME
for$PRICE/share

onasingleline.Inthefollowingexample:

Version102414
2014RegentsoftheUniversityofMichigan

0SELLER_1SELLGOOG$125#10
0SELLER_2SELLGOOG$100#10
0SELLER_3SELLGOOG$100#10
0SELLER_3SELLGOOG$80#10
0BUYER_1BUYGOOG$200#4

youshouldprint:

BUYER_1purchased4sharesofGOOGfromSELLER_3for$80/share

NotradescanbeexecutedonanequityforagivenCURRENT_TIMESTAMPifthereisnobuyerwillingtopay
thelowestaskingpriceofanyseller.Anexampleofsuchascenariois:
0BUYER_1BUYGOOG$100#50
0SELLER_1SELLGOOG$200#10
0BUYER_2BUYGOOG$150#3
0SELLER_2SELLGOOG$175#30

MedianOption
Ifandonlyifthemedianoptionisspecifiedonthecommandline,atthetimesdescribedintheMarketLogic
section(above),yourprogramshouldprintthecurrentmedianmatch priceofallcompletedtradesforeach
equitythatwereexecutedinthetimeinterval[0,CURRENT_TIMESTAMP].Tobeclear,thisisthemedianofthe
matchpricesofthetradesthemselves.Thisdoesnotconsiderthequantitytradedineachtrade.Equitieswith
lexicographicallysmallerEQUITY_SYMBOLsmustbeprintedfirst.Ifnomatcheshavebeenmadeona
particularequity,donotprintamedianforit.Ifthereareanevennumberoftrades,taketheaverageofthe
middlemosttwotocomputethemedian.Theoutputformatis:

MedianmatchpriceofEQUITY_SYMBOLattimeCURRENT_TIMESTAMPis$MEDIAN_PRICE

TransfersOption
Ifandonlyifthetransfersoptionisspecifiedonthecommandline,youshouldprintthefollowing
informationforeachclientwhoplacedanorderduringtherunoftheprogram:

CLIENT_NAMEboughtNUMBER_OF_STOCKS_BOUGHTandsoldNUMBER_OF_STOCKS_SOLDfora
nettransferof$NET_VALUE_TRADED

Thisshouldbeprintedsuchthatclientswithlexicographicallysmallerclientnamesareprintedfirst(see
operator<forstd::strings).TheNET_VALUE_TRADEDdoesnotincludecommissions.

Version102414
2014RegentsoftheUniversityofMichigan

10

TimeTravelTradingOption
Ifandonlyifthetttoption(TimeTravelTrading)isspecifiedonthecommandline,youshoulddothe
following:

Ifthetttoptionisspecifiedmorethanonce,youshouldprinttheresultsforeachEQUITY_SYMBOLthatis
giveninthesameorderthattheyweregiveninthecommandline.Inotherwords,ifthecommandlinehadboth
tttMSFTandthentttIBM,youwouldprintMSFTsinformationbeforeIBMs.Wewillnotspecifythe
sameequitytwice.

Intimetraveltrading,youareatimetravelerthatwantstofindtheidealtimesthatyoucouldhaveboughtan
2
equityandthenlatercouldhavesoldthatequitytomaximizeprofit (orifitisnotpossibletoprofit,todothis
whileminimizinglosses).YourprogramwillprintaTIMESTAMP1andTIMESTAMP2correspondingtothetimes
youcouldhaveplacedorderstodothis.

WhatthismeansisthatTIMESTAMP1willbethesameassomeactualsellorderthatcameinduringtheday,
andthatTIMESTAMP2willbethesameassomeactualbuyorderthatcameinafterthesellorder(withahigher
IDnumber).Theassumptionisthatthetimetravelerwouldhaveplacedthoseordersimmediatelyafterthe
actualorders.

Whencalculatingtheresultsfortimetraveltrading,theonlyfactorsarethetimeandpriceofordersthat
happenedthroughouttheday.Quantityisnotconsidered.Onewaytothinkaboutthisistoimagine(onlyforthe
purposeoftimetraveltrading)thatallordersareforunlimitedquantity.

Iftherewouldbemorethanoneanswerthatyieldstheoptimalresult,youshouldpreferanswerswithlower
timestamps.Ifduringthedaythereisnotatleastoneactualsellorderfollowedbyatleastoneactualbuyorder,
thenTIMESTAMP1andTIMESTAMP2shouldbothbeprintedas1.Makesuretoalsoconsiderinsidertradesif
aninsiderisused.

Theoutputformatisasfollows:

TimetravelerswouldbuyEQUITY_SYMBOLattime:TIMESTAMP1andsellitattime:
TIMESTAMP2

HelpOption
Ifandonlyifthehelpoptionisspecifiedonthecommandline,youshouldprintahelpfulmessageabout
theusagetostd::coutandthenexit(0)theprogramwithoutexecutinganytrades.

TheBestTimetoBuyandSellStockproblemathttp://leetcode.com/onlinejudgecorrespondstowhatweareaskingfor.
Thesiteincludesafreeautograder,soyoucandevelopandtestthisalgorithmseparatelyfromtherestofyourproject.
Version102414
2014RegentsoftheUniversityofMichigan

11

Insiders
Creation
Ifandonlyiftheinsideroptionisspecifiedonthecommandline,youshoulddothefollowing:

Theinsideroptioncanbespecifiedmorethanonceinordertouseaninsidetraderonmorethanone
equity.However,wewillneverspecifythesameequitytwice.

Eventhoughyouwillbemakingafairamountofmoneythroughthecommissionscollectedinyourprogram,
youwouldliketouseyourcontrolofthemarkettoyouradvantage.Becauseyouareatthecontrolofthisequity
tradingprogram,youhavetheabilitytoinsertnewordersimmediatelyintothequeueafterreadingeachnew
orderbeingplaced.Thiswillgiveyouan(unfair)advantagetobeabletoreactfasterthaneveryoneelsetothe
market.Notehowever,thatyouwillbeunabletochangewhatordershavealreadyhavebeenplacedinthepast
andcannotsupercedethem.

Aninsiderbehavesjustlikeanyotherclientandshouldbeaddedintoyourclientdatastructureatthebeginning
ofprogramexecution,astheydonotappearintheinputfilestream.Thenameoftheinsiderclientwillbethe
followingformat:

INSIDER_+EQUITY_SYMBOL

Forexample,iftheflaginsiderAMDwasgivenonthecommandlinethenaninsiderclientnamed
INSIDER_AMDwouldbecreated.NotethatthismeansthatclientnamesthatbeginwithINSIDER_are
reserved.

Logic
Afteranorderfromtheinputstreamhasbeenreadinandprocessed(seeMarketLogic)theprogramwillcheck
toseeifaninsiderexistsfortherecentlytradedequity.Next,itcheckstomakesurethatavalidmediantrade
valueexists,ascalculatedintheMediansection.Otherwise,itdoesnotattemptabuyorsell.

Notethatinthissystem,profitisdefinedasthemedianvalueoftheequityversustheactualpricepaidtoyouor
theseller.Forexample,ifthemedianofanequityis$90andyoupay$70foritspurchase,yourprofitis$20.
Eventhoughyoulostmoney,youpotentiallygainedmorevalueintheequity.Notethatprofitsarecalculated
onapersharebasis.

Theinsiderwillthenattempttoaddasinglebuyimmediatelytotheinputqueueatthecurrenttimestamp.Check
theminimumsellpriceforthatequity,andalsodeterminethenumberofsharesstillavailableforthissellorder.
Iftheprofitofthistransactionwouldbestrictlygreaterthan10%ofthemedian,addtheinsiderclientasabuyer
ofallremainingsharesandimmediatelymatchclientstooneanother.Notethattheinsiderwillbehavejust
Version102414
2014RegentsoftheUniversityofMichigan

12

likeanyotherclient(e.g.updatemediancalculation).

Theinsiderwillalsothenattempttoaddasinglesellimmediatelytotheinputqueueatthecurrenttimestamp.
Checkthecurrentmarketmaximumbuypriceandalsodeterminethenumberofsharesstillavailableforthis
order.Iftheprofitofthistransactionwouldbegreaterthan10%ofthemedian,addtheinsiderclientasaseller
ofallremainingsharesandimmediatelymatchclientstooneanother.

NotethatMarketLogicdictatesthattheinsidermustattempttoplaceabuyorderbeforeasellorder.Alsonote
thattheclientdoesnothaveabudgeteitherintermsofmoneyorsharesofitsequityandcansellandbuyasit
desires.

Output
Notethatbecauseaninsiderbehavesthesameasanyotherclient,thesameoutputwillbeexpectedforthe
transfersandverboseoptions.Inaddition,notethatalltradesshouldbeperformedexactlythesame
withaportionoftheprofitsbeingpaidtocommission.Youcanattributethistotheneedtonotraiseany
suspicionsbyhavingacertainclientreceivespecialprivileges(besidestheearlyaccessbit).

InsiderOutputExample
Input:
TL
0PlanetExpressSELLAMD$120#32
1BadWolfCorpBUYAMD$150#20
2BluthCorpSELLAMD$100#50
3KrustyKrabBUYAMD$200#10
4PlanetExpressBUYAMD$210#50
5BadWolfCorpBUYAMD$205#70
6BluthCorpBUYAMD$210#30
7KrustyKrabBUYAMD$205#40
8PlanetExpressSELLAMD$155#25

Outputwhenrunwithverbose,median,iAMD:
BadWolfCorppurchased20sharesofAMDfromPlanetExpressfor$120/share
MedianmatchpriceofAMDattime1is$120
INSIDER_AMDpurchased50sharesofAMDfromBluthCorpfor$100/share
MedianmatchpriceofAMDattime2is$110
KrustyKrabpurchased10sharesofAMDfromPlanetExpressfor$120/share
MedianmatchpriceofAMDattime3is$120
PlanetExpresspurchased2sharesofAMDfromPlanetExpressfor$120/share
PlanetExpresspurchased48sharesofAMDfromINSIDER_AMDfor$210/share
MedianmatchpriceofAMDattime4is$120
BadWolfCorppurchased70sharesofAMDfromINSIDER_AMDfor$205/share
Version102414
2014RegentsoftheUniversityofMichigan

13

MedianmatchpriceofAMDattime5is$120
BluthCorppurchased30sharesofAMDfromINSIDER_AMDfor$210/share
MedianmatchpriceofAMDattime6is$120
KrustyKrabpurchased40sharesofAMDfromINSIDER_AMDfor$205/share
MedianmatchpriceofAMDattime7is$162
MedianmatchpriceofAMDattime8is$162
EndofDay

Again,notethatthemedianisbasedonthepersharepriceofeachenactedtrade,notthenumberof
ordersplaced.

FullOutputExample
Input:
TL
0PlanetExpressSELLAMD$120#32
0BadWolfCorpBUYGE$200#20
0BluthCorpBUYAMD$100#50
1KrustyKrabBUYAMD$130#10
1PlanetExpressSELLGE$150#50
1PlanetExpressBUYNFLX$80#15
3BluthCorpSELLAMZN$50#22
4BadWolfCorpSELLGE$50#15
4BadWolfCorpSELLAMZN$100#30
4KrustyKrabBUYAMZN$130#12
4BadWolfCorpBUYAMZN$50#30
5BadWolfCorpSELLAMZN$50#5
5BluthCorpBUYAMD$150#25
6PlanetExpressSELLAMD$80#100
6BadWolfCorpBUYAMD$120#10
6KrustyKrabBUYGE$110#10
6BluthCorpBUYGE$200#25

Outputwhenrunwithverbose,s,median,transfers,iAMD,iGE,andtttAMZN:
KrustyKrabpurchased10sharesofAMDfromPlanetExpressfor$120/share
BadWolfCorppurchased20sharesofGEfromPlanetExpressfor$200/share
INSIDER_GEpurchased30sharesofGEfromPlanetExpressfor$150/share
MedianmatchpriceofAMDattime1is$120
MedianmatchpriceofGEattime1is$175
MedianmatchpriceofAMDattime3is$120
MedianmatchpriceofGEattime3is$175
INSIDER_GEpurchased15sharesofGEfromBadWolfCorpfor$50/share
Version102414
2014RegentsoftheUniversityofMichigan

14

KrustyKrabpurchased12sharesofAMZNfromBluthCorpfor$50/share
BadWolfCorppurchased10sharesofAMZNfromBluthCorpfor$50/share
MedianmatchpriceofAMDattime4is$120
MedianmatchpriceofAMZNattime4is$50
MedianmatchpriceofGEattime4is$150
BadWolfCorppurchased5sharesofAMZNfromBadWolfCorpfor$50/share
BluthCorppurchased22sharesofAMDfromPlanetExpressfor$120/share
BluthCorppurchased3sharesofAMDfromINSIDER_AMDfor$150/share
MedianmatchpriceofAMDattime5is$120
MedianmatchpriceofAMZNattime5is$50
MedianmatchpriceofGEattime5is$150
BluthCorppurchased50sharesofAMDfromPlanetExpressfor$100/share
INSIDER_AMDpurchased50sharesofAMDfromPlanetExpressfor$80/share
BluthCorppurchased25sharesofGEfromINSIDER_GEfor$200/share
MedianmatchpriceofAMDattime6is$120
MedianmatchpriceofAMZNattime6is$50
MedianmatchpriceofGEattime6is$175
EndofDay
CommissionEarnings:$574
TotalAmountofMoneyTransferred:$28890
NumberofCompletedTrades:12
NumberofSharesTraded:252
BadWolfCorpbought35andsold20foranettransferof$3750
BluthCorpbought100andsold22foranettransferof$11990
INSIDER_AMDbought50andsold3foranettransferof$3550
INSIDER_GEbought45andsold25foranettransferof$250
KrustyKrabbought22andsold0foranettransferof$1800
PlanetExpressbought0andsold182foranettransferof$21340
TimetravelerswouldbuyAMZNattime:3andsellitattime:4

LibrariesandRestrictions
WehighlyencouragetheuseoftheSTLforthisproject,withtheexceptionoftwoprohibitedfeatures:
TheC++11RegExlibrary(whoseimplementationingcc4.7isunreliable)andthethread/atomicslibraries
(whichspoilruntimemeasurements).Donotuseotherlibraries(e.g.,boost,pthreads,etc).

TestingandDebugging
Partofthisprojectistoprepareseveraltestcasesthatwillexposedefectsinbuggysolutionsyourownor
someoneelses.Asthisshouldbeusefulfortestinganddebuggingyourprograms,westronglyrecommend
thatyoufirsttrytocatchafewofourintentionallybuggysolutionswithyourtestcases,beforecompletingyour
Version102414
2014RegentsoftheUniversityofMichigan

15

solution.Theautograderwillalsotellyouifoneofyourowntestcasesexposesbugsinyoursolution.
Eachtestcaseshouldconsistofaninputfile.Whenwerunyourtestcasesononeofintentionallybuggy
projectsolutions,wecomparetheoutputtothatofacorrectprojectsolution.Iftheoutputsdiffer,thetestcase
issaidtoexposethatbug.
Testcasesshouldbenamedeither:
testnFLAG.txt
or
testnFLAGEQUITY_SYMBOL.txt
where0<n<=15,FLAGisone(andonlyone)ofv,m,t,i,s,org,andEQUITY_SYMBOLisastringthat
wouldbeallowed(asstatedintheinputsection)asapossibleequitysymbol(onlyforiorgflags).
Forexample:test1w.txtandtest2gAMZN.txtarebothvalidtestcasenames.Notethat
whenevertheiisselected,thevwillalsobeautomaticallybeselected.Thisisbecauseibyitself
willnotgenerateanyoutput.Notethatwhenrunningtheprogramnormally,ibyitself(plusitsequityname)is
stillconsideredavalidflagset.
YourtestcasesmustbeTradeListinputfiles,andmayhavenomorethan30linesinanyonefile.Youmay
submitupto15testcases(thoughitispossibletogetfullcreditwithfewertestcases).Notethatthetestson
whichtheautograderrunsyoursolutionareNOTlimitedto30linesinafileyoursolutionshouldnotimpose
anysizelimits(aslongassufficientsystemmemoryisavailable).

Whendebugging,wehighlyrecommendsettingupyourownsystemforquick,automated,regressiontesting.
Inotherwords,checkyoursolutionagainsttheoldoutputfromyoursolutiontoseeifithaschanged.Thiswill
saveyoufromwastingsubmits.YoumayfindtheLinuxutilitydiffusefulaspartofthis.

SubmittingtotheAutograder
Doallofyourwork(withallneededfiles,aswellastestcases)insomedirectoryotherthanyourhome
directory.Thiswillbeyoursubmitdirectory.Beforeyouturninyourcode,besurethat:
Youhavedeletedall.ofilesandyourexecutable(s).Typingmakecleanshallaccomplishthis.
YourmakefileiscalledMakefile.TypingmakeRrbuildsyourcodewithouterrorsandgeneratesan
executablefilecalled"market".(NotethatthecommandlineoptionsRandrdisableautomaticbuild
rules,whichwillnotworkontheautograder).
YourMakefilespecifiesthatyouarecompilingwiththegccoptimizationoptionO3.Thisisextremely
importantforgettingalloftheperformancepoints,asO3canspeedupcodebyanorderofmagnitude.
Yourtestcasefilesarenamedasdescribedaboveandnootherprojectfilenamesbeginwithtest.Upto
15testcasesmaybesubmitted.
Thetotalsizeofyourprogramandtestcasesdoesnotexceed2MB.
Youdon'thaveanyunnecessaryfiles(includingtemporaryfilescreatedbyyourtexteditorandcompiler,
etc)orsubdirectoriesinyoursubmitdirectory(e.g.,the.gitfolderusedbygitsourcecode
Version102414
2014RegentsoftheUniversityofMichigan

16

management).
Yourcodecompilesandrunscorrectlyusingversion4.7.0oftheg++compiler.Thisisavailableonthe
CAENLinuxsystems(thatyoucanaccessvialogin.engin.umich.edu).Evenifeverythingseemstowork
onanotheroperatingsystemorwithdifferentversionsofGCC,thecoursestaffwillnotsupportanything
otherthanGCC4.7.0runningonLinux(studentsusingothercompilersandOSdidobserve
incompatibilities).Note****:Tocompilewithg++version4.7.0onCAENyoumustputthefollowingat
thetopofyourMakefile:
PATH:=/usr/um/gcc4.7.0/bin:$(PATH)
LD_LIBRARY_PATH:=/usr/um/gcc4.7.0/lib64
LD_RUN_PATH:=/usr/um/gcc4.7.0/lib64

Turninallofthefollowingfiles:
Allyour.handor.cppfilesfortheproject
YourMakefile
Yourtestcasefiles
Youmustprepareacompressedtararchive(.tar.gzfile)ofallofyourfilestosubmittotheautograder.Oneway
todothisistohaveallofyourfilesforsubmission(andnothingelse)inonedirectory.Inthisdirectory,run
dos2unixU*tarczf./submit.tar.gz*.cpp*.hMakefiletest*.txt
Thiswillprepareasuitablefileinyourwormrkingdirectory.

Submityourprojectfilesdirectlytoeitherofthetwoautogradersat:
https://g2811.eecs.umich.edu/orhttps://g2812.eecs.umich.edu/.Notethatwhentheautogradersare
turnedonandacceptingsubmissions,therewillbeanannouncementonPiazza.Theautogradersare
identicalandyourdailysubmissionlimitwillbeshared(andkepttrackof)betweenthem.Youmaysubmitupto
threetimespercalendardaywithautograderfeedback.Forthispurpose,daysbeginandendatmidnight(Ann
Arborlocaltime).Wewillcountonlyyourlastsubmissionforyourgrade.Partoftheprogrammingskillis
knowingwhenyouaredone(whenyouhaveachievedyourtaskandhavenobugs)thisisreflectedinthis
gradingpolicy.Werealizethatitispossibleforyoutoscorehigherwithearliersubmissionstotheautograder
howeverthiswillhavenobearingonyourgrade.Westronglyrecommendthatyouusesomeformofrevision
control(ie:SVN,GIT,etc)andthatyoucommityourfileseverytimeyouuploadtotheautogradersothatyou
canalwaysretrieveanolderversionofthecodeasneeded.PleaserefertoyourdiscussionslidesandCTools
regardingtheuseofversioncontrol.

Pleasemakesurethatyoureadallmessagesshownatthetopsectionofyourautograderresults!
Thesemessagesoftenhelpexplainsomeoftheissuesyouarehaving(suchaslosingpointsfor
havingabadMakefileorwhyyouaresegfaulting).Alsobesuretonoteiftheautogradershowsthat
oneofyourowntestcasesexposesabuginyoursolution(atthebottom).

Grading
90pointsYourgradewillbederivedfromcorrectnessandperformance(runtime).Detailswillbedetermined
bytheautograder.
Version102414
2014RegentsoftheUniversityofMichigan

17

10pointsTestcasecoverage(effectivenessatexposingbuggysolutions).

Wealsoreservetherighttodeductupto5pointsforbadprogrammingstyle,codethatis
unnecessarilyduplicated,etc.

RefertotheProject1specfordetailsaboutwhatconstitutesgood/badstyle.

HintsandAdvice
Theprojectisspecifiedsothatthevariouspiecesofoutputareallindependent.Westronglyrecommend
workingonthemseparately,implementingonecommandlineoptionatatime.Theautograderhassometest
caseswhicharenamedsothatyoucangetasenseofwhereyourbugsmightbetheresaMEDcase,aTTT
case,aTransferscase,aVerbosecase,etc.

Wewillbeplacingastrongeremphasisontimebudgetsinthisproject.Thismeansthatyoumayfindthatyou
needtorewritesectionsofcodethatareperformingtooslowlyorchangedatastructures.Payattentiontothe
bigOhcomplexitiesofyourimplementationandexaminethetradeoffsofusingdifferentpossiblesolutions.
UsingGProfonthisprojectwillbeincrediblyhelpfulinfindingwhichpartsofyourcodearetakingupthemost
amountoftime.

Runningyourcodelocallyinvalgrindcanhelpyoufindandremoveundefined(buggy)behaviorandmemory
leaksfromyourcode.Thiscansaveyoufromlosingpointsinthefinalrunwhenyoumistakenlybelieveyour
codetobecorrect.

Itisextremelyhelpfultocompileyourcodewiththefollowinggccoptions:WallWextraWconversion
pedantic.Thiswaythecompilercanwarnyouaboutpoorstyleandpartsofyourcodethatmayresultin
unintended/undefinedbehavior.

Makesurethatyouareusinggetopt_longforhandlingcommandlineoptions.

Version102414
2014RegentsoftheUniversityofMichigan

18

AppendixA:IntegerCalculations
Obeythefollowingruleswhenmakingcalculationsinthisprogram:
1 Thetermintegerinthisdocumentspeakstointegerrepresentation.Forthepurposeofthisproject,you
shouldalwaysusetheC++typelonglongtorepresentintegersandavoidoverflowissues.Neveruse
floatsordoublesinthisproject,andinparticulardonotuselibraryfunctionsforroundingtointegers.
Considertypedefingyourowntype,e.g.:
typedeflonglongBigInt
Thereafter,youwillonlyneedtowriteBigIntandnotlonglong.
2 Whenorderofoperationscanbechanged,alwaysperformmultiplicationsbeforedivisions,unless
explicitlyrequestedotherwise.
3 Usetheclosestrepresentationoftheformulasweprovideinthespecinyourcode.Donotattemptto
combinecalculationsortakeshortcuts.Weexpectthatthemainspeedupsinthisprojectaregoingto
beindatastructuresratherthaninarithmeticoperations(atleastwhenthenumberoftradesislarge).

Version102414
2014RegentsoftheUniversityofMichigan

Potrebbero piacerti anche