File book.m:


// Book.m


#import "Book.h"
#include <time.h>
#import "BasicSumAgent.h" // this is placed here to avoid a circular call


// functions


void message(id <Index> agentArrayIndex, int n, float p, int bn)
{
BasicSumAgent * anAgent;
[agentArrayIndex setOffset: n-1];
anAgent=[agentArrayIndex get];
[anAgent setConfirmationOfExecutedPrice: p inBook: bn];
return;
}

void confirmationMessage(id <Index> agentArrayIndex, int n, float p, int bn)
{
BasicSumAgent * anAgent;
[agentArrayIndex setOffset: n-1];
anAgent=[agentArrayIndex get];
[anAgent orderConfirmationFrom: (int) bn atPrice:(float) p];
return;
}

void setLocal(Matrix2 * loc, float p)
{
int i;
if (p==0)return;
for (i=[loc getRows]-2;i>=0;i--)[loc R:i+1 C:0 setFrom: [loc R:i C:0]];
[loc R:0 C:0 setFrom: p];
return;
}

int getLocal(Matrix2 * loc)
{
int i, tot;
tot=0;
for (i=0;i<[loc getRows];i++)
{
if([loc R:i C:0]>0)tot++;
if([loc R:i C:0]<0)tot--;
}
return tot;
}


@implementation Book


// we set the book number
- setNumber: (int) n
{
theBookNumber = n;
return self;
}

- setContinuosMarket: (int) n
{
continuosMarket = n;
return self;
}


- setAgentArrayIndex: i
{
agentArrayIndex = i;
return self;
}

- setIndexCalculator: i
{
indexCalculator = i;
return self;
}

- setAgentNumber: (int) n
{
agentNumber=n;
return self;
}

- setMaxOrderQuantity: (int) m
{
maxOrderQuantity=m;
return self;
}

- setMeanPriceHistoryLength: (int) l
{
meanPriceHistoryLength=l;
return self;
}

- setPriceVolumesHistoryLength: (int) l
{
priceVolumesHistoryLength=l;
return self;
}

- setQuantityVolumesHistoryLength: (int) l
{
quantityVolumesHistoryLength=l;
return self;
}

- setLocalHistoryLength: (int) l
{
localHistoryLength=l;
return self;
}

- setFutureBook: (int) fb
{
futureBook=fb;
return self;
}

- setPrinting: (int) p
{
printing=p;
return self;
}

- createEnd
{
int i;
[super createEnd];

if (continuosMarket==1){
char webdataFileName2 [40];
sprintf(webdataFileName2,"lastSingle%d.dat",theBookNumber);
FILE * ppFile;
ppFile = fopen (webdataFileName2,"r");
if (ppFile != NULL) {
fscanf(ppFile,"%f", &oldPrice);
executedPrice=oldPrice;
meanPrice=oldPrice;
}else{
executedPrice=1;
meanPrice=1;
}
}else{
executedPrice=1; // this is the starting price; it seems to be
// not relevant at all for the behavior of the model
meanPrice=1;
}

previousClosingPrice=executedPrice;
currentMeanPrice=0;
count=0;
acceptedOrder=0;
quantityVolumes=0;
priceVolumes=0;
openingPrice=0.0;
lowPrice=0.0;
highPrice=0.0;
firstPrice=0;
controlPrice=executedPrice;


// the book works on the basis of two matrixes containing sell
// order in increasing order or buy order in decreasing order
// (in col 1 we have the orders; in col 2 the number of the agent
// placing the order)

// if an order obtains an immediate matching, it is not filed

// the worse situation is that of having all the order on one side of
// the market and all the agents ordering; so the rows of the two
// matrixes must be equal to the number of the agents

sellOrderStorehouse=[Matrix2 createBegin: [self getZone]];
[sellOrderStorehouse setDimensionRows: agentNumber*maxOrderQuantity
Cols: 2 Code: 1];
sellOrderStorehouse=[sellOrderStorehouse createEnd];

buyOrderStorehouse=[Matrix2 createBegin: [self getZone]];
[buyOrderStorehouse setDimensionRows: agentNumber*maxOrderQuantity
Cols: 2 Code: 2];
buyOrderStorehouse=[buyOrderStorehouse createEnd];

meanPriceHistory=[Matrix2 createBegin: [self getZone]];
[meanPriceHistory setDimensionRows: meanPriceHistoryLength
Cols: 1 Code: 3];
meanPriceHistory=[meanPriceHistory createEnd];
// mean prices will be stored by rows; now we fill all the r. with
// the starting mean price
for (i=0;i<=meanPriceHistoryLength-1;i++)
[meanPriceHistory R:i C:0 setFrom: meanPrice];

// the same for volumes
priceVolumesHistory=[Matrix2 createBegin: [self getZone]];
[priceVolumesHistory setDimensionRows: priceVolumesHistoryLength
Cols: 1 Code: 5];
priceVolumesHistory=[priceVolumesHistory createEnd];

for (i=0;i<=priceVolumesHistoryLength-1;i++)
[priceVolumesHistory R:i C:0 setFrom: priceVolumes];


quantityVolumesHistory=[Matrix2 createBegin: [self getZone]];
[quantityVolumesHistory setDimensionRows: quantityVolumesHistoryLength
Cols: 1 Code: 6];
quantityVolumesHistory=[quantityVolumesHistory createEnd];

for (i=0;i<=quantityVolumesHistoryLength-1;i++)
[quantityVolumesHistory R:i C:0 setFrom: quantityVolumes];


localHistory=[Matrix2 createBegin: [self getZone]];
[localHistory setDimensionRows: localHistoryLength
Cols: 1 Code: 4];
localHistory=[localHistory createEnd];
// local actions will be stored by rows; we fill all the r. with
// 0, i.e. 'no action', automatically, as a byproduct of the
// setDimensionRows:Cols: method


auctionMatrix=[Matrix2 createBegin: [self getZone]];
[auctionMatrix setDimensionRows: agentNumber*2 Cols: 5 Code: 7];
auctionMatrix=[auctionMatrix createEnd];

return self;
}

// at the end of each day
- setMeanPrice{
if (count>0) meanPrice=currentMeanPrice/count; // otherwise we keep
// previous value
return self;
}

- setNAheadForecasting: (int) na
{
nAheadForecasting = na;
return self;
}

// at the beginning of each day
- setClean{
int i;
sellOrderNumber=0; buyOrderNumber=0;

// meanPriceHistory in row 0 contains the t-1 meanPrice;
// in row 1 contains the t-2 meanPrice;
// etc.
for (i=meanPriceHistoryLength-2;i>=0;i--)
[meanPriceHistory R:i+1 C:0 setFrom:
[meanPriceHistory R:i C:0]];
[meanPriceHistory R:0 C:0 setFrom: meanPrice];

for (i=priceVolumesHistoryLength-2;i>=0;i--)
[priceVolumesHistory R:i+1 C:0 setFrom:
[priceVolumesHistory R:i C:0]];
[priceVolumesHistory R:0 C:0 setFrom: priceVolumes];

for (i=quantityVolumesHistoryLength-2;i>=0;i--)
[quantityVolumesHistory R:i+1 C:0 setFrom:
[quantityVolumesHistory R:i C:0]];
[quantityVolumesHistory R:0 C:0 setFrom: quantityVolumes];

previousClosingPrice=executedPrice; // the last one of 'yesterday'
currentMeanPrice=0;
count=0;
acceptedOrder=0;
quantityVolumes=0;
priceVolumes=0;
openingPrice=0.0;
lowPrice=0.0;
highPrice=0.0;
firstPrice=0;
return self;
}

// receiving an order before opening from an agent
- setOrderBeforeOpeningFromAgent: (int) n atPrice: (float) p
{
int number;
number = n;
price = p;

if((price!=0)&&((abs(price)>controlPrice*1.90)||(abs(price)<controlPrice*0.10))){
if(printing==1)printf("The order on book #%3d from agent #%3d at price %7.4f is out of 90 per cent controlPrice range.\n",theBookNumber, number, price);
return self;
}

if(printing==1)printf("The book #%3d received an auction order from agent #%3d at price %7.4f\n",theBookNumber, number, price);

// local history
setLocal(localHistory, price);

// if price==0 no action required, but sending a 0.0 message to the agent
if(price==0) message(agentArrayIndex, number, 0.0, theBookNumber);

// the agent is selling at min price '-price'
if(price<0) {
message(agentArrayIndex, number, 0.0, theBookNumber);
// filing the sell order, in increasing order
sellOrderNumber++;
acceptedOrder++;
[sellOrderStorehouse fileIncreasingP: -price
andN: (float) number
usingAsNumberOfRows: sellOrderNumber];
if(printing==1)
[sellOrderStorehouse printNRows: sellOrderNumber];
[sellOrderStorehouse printNRowsFileS: sellOrderNumber ofBook: theBookNumber];
}

// the agent is buying at max price 'price'
if(price>0) {
message(agentArrayIndex, number, 0.0, theBookNumber);
// filing the buy order, in decreasing order
buyOrderNumber++;
acceptedOrder++;
[buyOrderStorehouse fileDecreasingP: price
andN: (float) number
usingAsNumberOfRows: buyOrderNumber];
if(printing==1)
[buyOrderStorehouse printNRows: buyOrderNumber];
[buyOrderStorehouse printNRowsFileB: buyOrderNumber ofBook: theBookNumber];
}

return self;
}

// receiving an order when the market is open
- setOrderFromAgent: (int) n atPrice: (float) p
{

time_t tiempo;
char cad[80];
struct tm *tmPtr;
int number;
tiempo = time(NULL);
tmPtr = localtime(&tiempo);
strftime( cad, 80, "%d-%m-%Y %H:%M:%S", tmPtr );

number = n;
price = p;

if((price!=0)&&((abs(price)>controlPrice*1.90)||(abs(price)<controlPrice*0.10))){
if(printing==1)printf("The order on book #%3d from agent #%3d at price %7.4f is out of 90 per cent controlPrice range.\n",theBookNumber, number, price);
return self;
}

if(price!=0)acceptedOrder++;

if(printing==1) printf("The book #%3d received an order from agent #%3d at price %7.4f\n",theBookNumber, number, price);

// local history
setLocal(localHistory, price);

// if price==0 no action required, but sending a 0.0 message to the agent
if(price==0) message(agentArrayIndex, number, 0.0, theBookNumber);

// the agent is selling at min price '-price'
if(price<0) {if (buyOrderNumber>0 &&
[buyOrderStorehouse R: 0 C: 0] >= -price)
{executedPrice=[buyOrderStorehouse R: 0 C: 0];
currentMeanPrice+=executedPrice;
count++;
quantityVolumes++;
priceVolumes+=executedPrice;

[self printPrices: theBookNumber atPrice: executedPrice];

message(agentArrayIndex, number, -executedPrice, theBookNumber);
message(agentArrayIndex,(int)[buyOrderStorehouse R: 0 C: 1],
executedPrice, theBookNumber);
confirmationMessage(agentArrayIndex, number, -executedPrice, theBookNumber);
confirmationMessage(agentArrayIndex, (int)[buyOrderStorehouse R: 0 C: 1], executedPrice, theBookNumber);

buyOrderNumber--;
[buyOrderStorehouse shiftRowsDown: buyOrderNumber];
if(printing==1)
[buyOrderStorehouse printNRows: buyOrderNumber];
[buyOrderStorehouse printNRowsFileB: buyOrderNumber ofBook: theBookNumber];

if (firstPrice==0){
openingPrice=executedPrice;
lowPrice=executedPrice;
highPrice=executedPrice;
closingPrice=executedPrice;
firstPrice=1;
}
if (lowPrice>executedPrice) lowPrice=executedPrice;
if (highPrice<executedPrice) highPrice=executedPrice;
closingPrice=executedPrice;

}

else {
message(agentArrayIndex, number, 0.0, theBookNumber);
// filing the sell order, in increasing order
sellOrderNumber++;
[sellOrderStorehouse fileIncreasingP: -price
andN: (float) number
usingAsNumberOfRows: sellOrderNumber];
if(printing==1)
[sellOrderStorehouse printNRows: sellOrderNumber];
[sellOrderStorehouse printNRowsFileS: sellOrderNumber ofBook: theBookNumber];
}
}

// the agent is buying at max price 'price'
if(price>0) {if (sellOrderNumber>0 &&
[sellOrderStorehouse R: 0 C: 0] <= price)
{executedPrice=[sellOrderStorehouse R: 0 C: 0];
currentMeanPrice+=executedPrice;
count++;
quantityVolumes++;
priceVolumes+=executedPrice;

[self printPrices: theBookNumber atPrice: executedPrice];

message(agentArrayIndex, number, executedPrice, theBookNumber);
message(agentArrayIndex,(int)[sellOrderStorehouse R: 0 C: 1],
-executedPrice, theBookNumber);
confirmationMessage(agentArrayIndex, number, executedPrice, theBookNumber);
confirmationMessage(agentArrayIndex, (int)[sellOrderStorehouse R: 0 C: 1], -executedPrice, theBookNumber);

sellOrderNumber--;

[sellOrderStorehouse shiftRowsDown: sellOrderNumber];

if(printing==1)
[sellOrderStorehouse printNRows: sellOrderNumber];
[sellOrderStorehouse printNRowsFileS: sellOrderNumber ofBook: theBookNumber];

if (firstPrice==0){
openingPrice=executedPrice;
lowPrice=executedPrice;
highPrice=executedPrice;
closingPrice=executedPrice;
firstPrice=1;
}
if (lowPrice>executedPrice) lowPrice=executedPrice;
if (highPrice<executedPrice) highPrice=executedPrice;
closingPrice=executedPrice;

}

else {
message(agentArrayIndex, number, 0.0, theBookNumber);
// filing the buy order, in decreasing order
buyOrderNumber++;
[buyOrderStorehouse fileDecreasingP: price
andN: (float) number
usingAsNumberOfRows: buyOrderNumber];
if(printing==1)
[buyOrderStorehouse printNRows: buyOrderNumber];
[buyOrderStorehouse printNRowsFileB: buyOrderNumber ofBook: theBookNumber];


}

}

return self;
}


- (float) auction
{
int i, k, j;
executableOrders=0;
surelyExecutableOrders=0;
potentialBalanceness=0;
insertableInAuction=0;
j=0;
// scanning buyOrders

if((buyOrderNumber>0)&&(sellOrderNumber>0))
for(i=0;i<=buyOrderNumber-1;i++)
{
buyPrice=[buyOrderStorehouse R: i C: 0];
// check if there are equal prices (we use only the last one)
if (i==buyOrderNumber-1)
{executableOrders++;insertableInAuction=1;}
else {nextBuyPrice=[buyOrderStorehouse R: i+1 C: 0]; if(buyPrice!=nextBuyPrice){insertableInAuction=1;executableOrders++;}else{executableOrders++;}}

if (([sellOrderStorehouse R: 0 C: 0] <= buyPrice )&& (insertableInAuction==1)) {
// check the minimum between the number of Orders that can be executed and the number of counterparts
minimumExecutableOrders=executableOrders;if(executableOrders>sellOrderNumber)minimumExecutableOrders=sellOrderNumber;
// first rule
for(k=0;k<=minimumExecutableOrders-1;k++)
{
if([sellOrderStorehouse R: k C: 0] <= buyPrice) surelyExecutableOrders++;
}
// second rule
for(k=0;k<=sellOrderNumber-1;k++)
{
if([sellOrderStorehouse R: k C: 0] <= buyPrice) potentialBalanceness++;
}

balanceness=potentialBalanceness-surelyExecutableOrders;

//insert in auctionMatrix
[auctionMatrix fileAddP: buyPrice fromRow: i withExecutableOrders: surelyExecutableOrders withBalanceness:balanceness withAbsoluteDifference: fabs(buyPrice-controlPrice) usingAsNumberOfRows: j ];
// the respect of third rule is expressed by 'abs(buyPrice-controlPrice)' above

surelyExecutableOrders=0;
potentialBalanceness=0;
insertableInAuction=0;
j++;

}

}


executableOrders=0;
surelyExecutableOrders=0;
potentialBalanceness=0;
insertableInAuction=0;

// scanning sellOrders

if((buyOrderNumber>0)&&(sellOrderNumber>0))
for(i=0;i<=sellOrderNumber-1;i++)
{
sellPrice=[sellOrderStorehouse R: i C: 0];
if (i==sellOrderNumber-1)
{executableOrders++;insertableInAuction=1;}
else {nextSellPrice=[sellOrderStorehouse R: i+1 C: 0]; if(sellPrice!=nextSellPrice){executableOrders++;insertableInAuction=1;}else{executableOrders++;}}


if (([buyOrderStorehouse R: 0 C: 0] >= sellPrice) && (insertableInAuction==1)) {
minimumExecutableOrders=executableOrders;if(executableOrders>buyOrderNumber)minimumExecutableOrders=buyOrderNumber;
for(k=0;k<=minimumExecutableOrders-1;k++)
{
if([buyOrderStorehouse R: k C: 0] >= sellPrice)surelyExecutableOrders++;
}

for(k=0;k<=buyOrderNumber-1;k++)
{
if([buyOrderStorehouse R: k C: 0] >= sellPrice)potentialBalanceness++;
}

balanceness=potentialBalanceness-surelyExecutableOrders;

// check if the price is already in auctionMatrix from buyOrders
insertableInAuction=0;
for(k=0;k<=j-1;k++){
if([auctionMatrix R:k C:1]!=sellPrice){
// ok: there isn't in Matrix -> insert
insertableInAuction=1;

}else{
// we have 2 equal prices: check which is the best
insertableInAuction=0;
// the best for first rule
if([auctionMatrix R:j C:2]<surelyExecutableOrders){insertableInAuction=2;}
else if([auctionMatrix R:j C:2]==surelyExecutableOrders){
// the best for second rule
if([auctionMatrix R:j C:3]>balanceness){insertableInAuction=2;}
}

// this is the best: substitute the old price in auctionMatrix
if(insertableInAuction==2){
[auctionMatrix fileAddP: sellPrice fromRow: i withExecutableOrders: surelyExecutableOrders withBalanceness:balanceness withAbsoluteDifference: fabs(sellPrice-controlPrice) usingAsNumberOfRows: k ];

}


}

}

if(insertableInAuction==1){
//insert in auctionMatrix
[auctionMatrix fileAddP: sellPrice fromRow: i withExecutableOrders: surelyExecutableOrders withBalanceness:balanceness withAbsoluteDifference: fabs(sellPrice-controlPrice) usingAsNumberOfRows: j ];

j++;
}
surelyExecutableOrders=0;
potentialBalanceness=0;
insertableInAuction=0;

}
}

// determination (fourth rule)

maxSurelyExecutableOrders=-1;
minBalanceness=10000;
nearestControlPrice=10000;
auctionPrice=0.0;

if(printing==1){printf("AuctionMatrix\n");[auctionMatrix printNRows: j];}

if((buyOrderNumber>0)&&(sellOrderNumber>0))
for(i=0;i<=j;i++)
{
// check for the first rule better price
if([auctionMatrix R:i C:2]>maxSurelyExecutableOrders){auctionPrice=[auctionMatrix R:i C:1];maxSurelyExecutableOrders=[auctionMatrix R:i C:2]; minBalanceness=[auctionMatrix R:i C:3];nearestControlPrice=[auctionMatrix R:i C:4];auctionPriceRow=[auctionMatrix R:i C:0];}
else if([auctionMatrix R:i C:2]==maxSurelyExecutableOrders){
// check for the second rule better price
if([auctionMatrix R:i C:3]<minBalanceness){auctionPrice=[auctionMatrix R:i C:1];maxSurelyExecutableOrders=[auctionMatrix R:i C:2]; minBalanceness=[auctionMatrix R:i C:3];nearestControlPrice=[auctionMatrix R:i C:4];auctionPriceRow=[auctionMatrix R:i C:0];}
else if([auctionMatrix R:i C:3]==minBalanceness){
// check for the third rule better price
if([auctionMatrix R:i C:4]<nearestControlPrice){auctionPrice=[auctionMatrix R:i C:1];maxSurelyExecutableOrders=[auctionMatrix R:i C:2]; minBalanceness=[auctionMatrix R:i C:3];nearestControlPrice=[auctionMatrix R:i C:4];auctionPriceRow=[auctionMatrix R:i C:0];}
else if([auctionMatrix R:i C:4]==nearestControlPrice){
// check for the fourth rule better price
if([auctionMatrix R:i C:1]>auctionPrice){auctionPrice=[auctionMatrix R:i C:1];maxSurelyExecutableOrders=[auctionMatrix R:i C:2]; minBalanceness=[auctionMatrix R:i C:3];nearestControlPrice=[auctionMatrix R:i C:4];auctionPriceRow=[auctionMatrix R:i C:0];}
}
}
}
}

// validation
if((auctionPrice>1.1*controlPrice)||(auctionPrice<0.9*controlPrice)){auctionPrice=0.0;if(printing==1){printf("The AuctionPrice can't be validate.\n");}}

// exchange
if(auctionPrice!=0.0)
{
for(i=maxSurelyExecutableOrders-1;i>=0;i--)
{

message(agentArrayIndex,(int)[buyOrderStorehouse R: i C: 1], auctionPrice, theBookNumber);
message(agentArrayIndex,(int)[sellOrderStorehouse R: i C: 1], -auctionPrice, theBookNumber);

confirmationMessage(agentArrayIndex,(int)[buyOrderStorehouse R: i C: 1], auctionPrice, theBookNumber);
confirmationMessage(agentArrayIndex,(int)[sellOrderStorehouse R: i C: 1], -auctionPrice, theBookNumber);

buyOrderNumber--;
[buyOrderStorehouse shiftRowsDown: buyOrderNumber];

sellOrderNumber--;
[sellOrderStorehouse shiftRowsDown: sellOrderNumber];

quantityVolumes++;
priceVolumes+=executedPrice;

}

if(printing==1)
[buyOrderStorehouse printNRows: buyOrderNumber];
[buyOrderStorehouse printNRowsFileB: buyOrderNumber ofBook: theBookNumber];

if(printing==1)
[sellOrderStorehouse printNRows: sellOrderNumber];
[sellOrderStorehouse printNRowsFileS: sellOrderNumber ofBook: theBookNumber];

[self printPrices: theBookNumber atPrice: executedPrice];

}

if(printing==1){printf("The AuctionPrice on Book # %3d is %9.5f\n",theBookNumber,auctionPrice);};
return auctionPrice;
}

- openingAuction
{
if(printing==1){printf("*** Opening Auction - Book # %3d ***\n",theBookNumber);}
auctionPrice=[self auction];
if(auctionPrice!=0)
{
executedPrice=auctionPrice;
controlPrice=auctionPrice;
openingPrice=executedPrice;
closingPrice=executedPrice;
lowPrice=executedPrice;
highPrice=executedPrice;
firstPrice=1;
}else{
controlPrice=previousClosingPrice;
}
[self printControlPrice];
return self;
}

- closingAuction
{
if(printing==1){printf("*** Closing Auction - Book # %3d ***\n",theBookNumber);}
[self auction];
if(auctionPrice!=0)
{
executedPrice=auctionPrice;
controlPrice=auctionPrice;
closingPrice=executedPrice;
if (lowPrice>executedPrice) lowPrice=executedPrice;
if (highPrice<executedPrice) highPrice=executedPrice;
if(firstPrice==0){
firstPrice=1;
lowPrice=executedPrice;
highPrice=executedPrice;
openingPrice=executedPrice;
}
}
[self printControlPrice];
return self;
}


- printControlPrice
{
char webdataFileName [40];
sprintf(webdataFileName,"%d.controlprice",theBookNumber);

FILE * pFile;

pFile = fopen (webdataFileName,"w");
if (pFile == NULL) {
perror("cannot open output file1");
exit(1);
}
fprintf(pFile,"%7.4f\n",controlPrice);
fclose(pFile);
return self;
}

- printPrices: (int) n atPrice: (float) p
{
theBookNumber=n;
executedPrice=p;

time_t tiempo;
char cad[80];
struct tm *tmPtr;

tiempo = time(NULL);
tmPtr = localtime(&tiempo);
strftime( cad, 80, "%d-%m-%Y %H:%M:%S", tmPtr );

char webdataFileName [40];
sprintf(webdataFileName,"bookdata%d.dat",theBookNumber);
char webdataFileName2 [40];
sprintf(webdataFileName2,"lastSingle%d.dat",theBookNumber);
char webdataFileName3 [40];
sprintf(webdataFileName3,"lastSingleIndex.dat");


FILE * pFile;

pFile = fopen (webdataFileName,"a");
if (pFile == NULL) {
perror("cannot open output file1");
exit(1);
}

if(theBookNumber==futureBook){
indexValue=[indexCalculator getIndexValue];
fprintf(pFile,"%s %9.4f %9.4f\n",cad,executedPrice,indexValue);

FILE * pppFile;
pppFile = fopen (webdataFileName3,"w");
if (pppFile == NULL) {
perror("cannot open output file1");
exit(1);
}
fprintf(pppFile,"%7.4f\n",indexValue);
fclose(pppFile);

}else{fprintf(pFile,"%s %9.4f\n",cad,executedPrice);}

fclose(pFile);

FILE * ppFile;

ppFile = fopen (webdataFileName2,"w");
if (ppFile == NULL) {
perror("cannot open output file5");
exit(1);
}
fprintf(ppFile,"%7.4f\n",executedPrice);
fclose(ppFile);
return self;
}


- (float) getPrice
{
return executedPrice;
}

- (float) getMeanPrice
{
return meanPrice;
}

- (float) getLaggedMeanPrice: (int) lag
{
return [meanPriceHistory R: lag-1 C: 0];
}

- (float) getMeanPriceIndex
{
return meanPrice/[meanPriceHistory R: nAheadForecasting C: 0];
}

- (int) getLocalHistory
{
return getLocal(localHistory);
}

- (float) getSellOrderNumber
{
return (float) sellOrderNumber;
}

- (float) getBuyOrderNumber
{
return (float) buyOrderNumber;
}

- (float) getPreviousClosingPrice
{
return previousClosingPrice;
}

- (float) getAskPrice
{
return [buyOrderStorehouse R: 0 C: 0];
}

- (float) getBidPrice
{
return [sellOrderStorehouse R: 0 C: 0];
}

- (int) getQuantityVolumes
{
return (int) quantityVolumes;
}

- (float) getPriceVolumes
{
return (float) priceVolumes;
}


- (float) getOpeningPrice
{
return openingPrice;
}

- (float) getClosingPrice
{
return closingPrice;
}

- (float) getLowPrice
{
return lowPrice;
}

- (int) getAcceptedOrder
{
return acceptedOrder;
}


- (float) getHighPrice
{
return highPrice;
}

@end

 

File scoretable.php:

<HTML>
<head>
<?php
require("conf.php");
echo "<meta http-equiv=Refresh CONTENT=\"$scoretablePageRefresh\">";
?>
<title>SumWeb: Scoretable</title>
</head>
<body>

<center>
<h1>Scoretable</h1>


<table border="1">
<tr><td align="center"><font face="Arial"><b>Rank</b></font></td>
<td align="center"><font face="Arial"><b>Name</b></font></td>
<td align="center"><font face="Arial"><b>Surname</b></font></td>
<td align="center"><font face="Arial"><b>Wealth</b></font></td>
<td align="center"><font face="Arial"><b>Penalty</b></font></td>
<td align="center"><font face="Arial"><b>Score</b></font></td></tr>

<?php

$fp = fopen('users.php', "r");
if (!$fp) {
echo "<p>Errore nell'apertura del file remoto.\n";
exit;
}

$i=1;

while ($userinfo = fscanf ($fp, "%i\t%s\t%s\t%s\t%s\n")) {
list ($number[$i], $username[$i],, $name[$i], $surname[$i]) = $userinfo;

$index=$number[$i];
$name2[$index]=$name[$i];
$surname2[$index]=$surname[$i];
if((file_exists('avatardata/'.$number[$i].'.penalty'))AND(file_exists('avatardata/'.$number[$i].'.wealth'))){
$fp2 = fopen('avatardata/'.$number[$i].'.penalty', "r");
if (!$fp2) {
echo "<p>Errore nell'apertura del file remoto.\n";
exit;
}
$penalty2=fscanf ($fp2, "%f");
list($penalty[$number[$i]])=$penalty2;

$fp3 = fopen('avatardata/'.$number[$i].'.wealth', "r");
if (!$fp3) {
echo "<p>Errore nell'apertura del file remoto.\n";
exit;
}
$wealth2=fscanf ($fp3, "%f");

list($wealth[$number[$i]])= $wealth2;

$score[$number[$i]]=$wealth[$number[$i]] + $penalty[$number[$i]];

fclose($fp2);
fclose($fp3);
}
$index=$i;
$i++;
}

fclose($fp);

if($score!=NULL){

arsort ($score);
reset ($score);

$rank=1;

while (list ($key, $value) = each ($score)) {
if ($rank <= 3){
echo "<tr bgcolor=\"#00FFFF\">";
}elseif (($rank>3)&&($rank<=5)){
echo "<tr bgcolor=\"#00FFCC\">";
}else{
echo "<tr>";
}
echo"<td align=\"center\">$rank</td> <td>$name2[$key]</td><td>$surname2[$key]</td><td align=\"right\">$wealth[$key]</td><td align=\"right\">$penalty[$key]</td><td align=\"right\"><b>$value</b></td></tr>\n";
$rank++;
}
}


?>
</table>
</center>
</body>
</html>




File questionnaire.php:

<?php
require("conf.php");
session_start();
session_register("iduserse");
session_register("fullname");
session_register("idmember");
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>SumWeb: Questionnaire</TITLE>
<META NAME="Generator" CONTENT="vi">
<META NAME="Author" CONTENT="k">
</HEAD>

<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" >
<center>

<center>
<img src="newlogo.jpg" width="246" height="119" align="middle" alt="SumWeb">
<p>


<br>


<p> Per cortesia compilate il questionario in tutte le sue parti


</center><form method="post" action="questionnaire2.php"><center>


<TABLE ALIGN="center" BORDER=1 CELLSPACING=0 CELLPADDING=0 >


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Sesso </TD>
<TD>
<table><tr><td><input name="sex" type="radio" value="M"></td><td>M</td><td><input type="radio" name="sex" value="F"></td><td>F</td></tr></table>
</TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Età</TD>
<TD> <input type="text" name="age" size="3" maxlength="3"> </TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Professione</TD>
<TD> <input type="text" name="profession" size="30" maxlength="60"> </TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Prima di partecipare all'esperimento avevi già fatto delle operazioni nella borsa reale ? </TD>
<TD>
<table><tr><td><input name="exp" type="radio" value="Y"></td><td>Sì</td><td><input type="radio" name="exp" value="N"></td><td>No</td></tr></table>
</TD></tr>

<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Il modello SumWeb e le sue caratteristiche corrispondono alla tua idea di mercato di borsa? </TD>
<TD>
<table><tr><td><input name="sumidea" type="radio" value="Y"></td><td>Sì</td><td><input type="radio" name="sumidea" value="N"></td><td>No</td></tr></table>
</TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Ritieni che ci siano troppe semplificazioni? Quali? </TD>
<TD>

<TEXTAREA wrap="soft" name="sumno" cols="30" rows="5">
</TEXTAREA> </TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Quali difficoltà hai trovato nell'uso del modello (riguardo all'interfaccia, alle informazioni che ti sono state fornite prima di iniziare e quelle che l'interfaccia ti ha fornito durante l'esperimento)? </TD>
<TD>

<TEXTAREA wrap="soft" name="difficult" cols="30" rows="5">
</TEXTAREA> </TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> E quali difficoltà riguardo alle decisioni di acquistare o vendere i titoli del modello? </TD>
<TD>

<TEXTAREA wrap="soft" name="decision" cols="30" rows="5">
</TEXTAREA> </TD></tr>


<TR ALIGN="left" VALIGN="middle">
<TD align="center"> Quale elemento ha guidato maggiormente le tue scelte di acquisto e vendita (l'ultimo prezzo, i grafici, i book...)?</TD>
<TD>

<TEXTAREA wrap="soft" name="element" cols="30" rows="5">
</TEXTAREA> </TD></tr>

<TR ALIGN="left" VALIGN="middle">
<TD align="center" colspan="2"> <input type="submit" name="Submit" value="Submit"> </TD></tr>

</TABLE>

</center></form>

</BODY>
</HTML>



File questionnaire2.php:

<?php
require("conf.php");
session_start();
session_register("iduserse");
session_register("fullname");
session_register("idmember");

$sex=$HTTP_POST_VARS[sex];
$age=$HTTP_POST_VARS[age];
$profession=$HTTP_POST_VARS[prefession];
$matricola=$HTTP_POST_VARS[matricola];
$exp=$HTTP_POST_VARS[exp];
$sumidea=$HTTP_POST_VARS[sumidea];
$sumno=$HTTP_POST_VARS[sumno];
$difficult=$HTTP_POST_VARS[difficult];
$decision=$HTTP_POST_VARS[decision];
$element=$HTTP_POST_VARS[element];

//addslashes
$difficult=addcslashes($difficult, "\0..\37!@\177..\377");
$sumno=addcslashes($sumno, "\0..\37!@\177..\377");
$decision=addcslashes($decision, "\0..\37!@\177..\377");
$difficult=addcslashes($difficult, "\0..\37!@\177..\377");
$element=addcslashes($element, "\0..\37!@\177..\377");

$adesso=getdate();
$dataoggi=$adesso['mday']."-".$adesso['mon']."-".$adesso['year']."--".$adesso['hours'].":".$adesso['minutes'].":".$adesso['seconds'];

$ipr = "$REMOTE_ADDR";

$fp = fopen("questionnaire.txt", "a");

if (!$fp) {
echo "<p>Errore nell'apertura del file remoto.\n";
exit;
}

$messagefile=$dataoggi."\t".$ipr."\t".$iduserse."\t".$fullname."\t".$idmember."\t".$sex."\t".$age."\t".$profession."\t".$exp."\t".$sumidea."\t".$sumno."\t".$difficult."\t".$decision."\t".$element."\n";


fwrite($fp, "$messagefile");

fclose($fp);
echo "<HTML><HEAD><TITLE>SumWeb: Questionnaire</TITLE></HEAD><center><img src=\"newlogo.jpg\" width=\"246\" height=\"119\" align=\"middle\" alt=\"SumWeb\"><p>";

echo "<center><h1>Thank You - Grazie</h1></center>";

?>


Capitolo 6
Indice
Capitolo 7