stock markt

download stock markt

of 41

Transcript of stock markt

  • 8/7/2019 stock markt

    1/41

  • 8/7/2019 stock markt

    2/41

    1 INTRODUCTION................................................................................................ 1 1.1 BACKGROUND ........................................................... .................................... 1 1.2 PROBLEM ........................................................ .............................................. 2 1.3 ASSIGNMENT ................................................... .............................................. 3 1.4 PURPOSE ......................................................... .............................................. 3 1.5 HYPOTHESIS .................................................... .............................................. 4 1.6 METHODOLOGY ........................................................ .................................... 4

    1.6.1 Goal fulfilment .................................................................. ....................... 4 1.6.2 Goals..................................................................... ................................... 4 1.6.4 Preparatory work .................................................................... ................ 4 1.6.5 Work method................ ..................................................................... ....... 5

    1.7 DELIMITATION .......................................................... .................................... 5 2 AGENT TRADE SERVER ................................................................ ................. 6

    2.1 R OLE ..................................................... ........................................................ 6 2.2 DESIGN .................................................. ........................................................ 6 2.3 R UNNING AGENTS ON THE ATS................................................... ................. 7

    3 REQUIREMENTS IN TRADING AGENT CONTEXT.................................. 8 3.1 PORTFOLIO ...................................................... .............................................. 8 3.2 MARKET INFORMATION ....................................................... .......................... 8 3.3 AGENT BROKER ........................................................ .................................... 9 3.4 K EEPING TRACK OF ACTIONS AND STATUS ................................................. 10 3.5 SECURITY ISSUES ...................................................... .................................. 11

    3.5.1 Availability .................................................................. .......................... 11 3.5.2 Integrity ............................................................ ..................................... 12 3.5.3 Authentication........................................... ............................................. 12 3.5.4 Confidentiality ..................................................................... .................. 12

    4 SERVICE PACKAGE FOR TRADING AGENTS ........................................ 13 4.1 PACKAGE DESIGN ..................................................... .................................. 13 4.2 SE.SICS .ATS .AGENT .TRADE AGENT ......................................................... ..... 14

    4.2.1 Initialising and Starting Subagents........................................................ 15 4.2.2 Stopping Subagents......................................................... ....................... 15 4.2.3 Retrieving Information about Stocks ..................................................... 15 4.2.4 Entering Orders............. ................................................................ ........ 15

    4.3 SE.SICS .ATS .AGENT .ACCOUNT ...................................................... ............... 16 4.4 SE.SICS .ATS .AGENT .PORTFOLIO .................................................... ............... 16 4.5 SE.SICS .ATS .AGENT .LOGHANDLER ......................................................... ..... 16

    4.5.1 Log methods................................................. .......................................... 17 4.6 SE.SICS .ATS .AGENT .AGENT BROKER ....................................................... ..... 17

    4.6.1 Deducting Brokerage Fee.................. .................................................... 18 4.7 SE.SICS .ATS .AGENT .COMPLEX ORDER .................................................. ........ 18

    4.7.1 Creating and Starting Complex Order .................................................. 18 4.8 ACCESS -LEVEL CONTROL ................................................... ........................ 18

    5 RESULT ....................................................... ...................................................... 20 5.1 TEST PREPARATIONS ...................................................... ............................. 20

    5.1.1 ATS Preparations ....................................................... ........................... 20 5.1.2 DayTrader Agent ....................................................... ............................ 20 5.1.3 Stock Development During Test ............................................................ 21

    5.2 TEST R ESULT ............................................................ .................................. 21 5.2.1 Agent Performance.............................................................. .................. 21 5.2.2 Comments About the Test .................................................................. .... 22

  • 8/7/2019 stock markt

    3/41

    6 CONCLUSION .................................................... .............................................. 24

    ACKNOWLEDGEMENTS................................................................. ....................... 26

    REFERENCES.............................................................. .............................................. 27

    APPENDIX A - AGENT LOG FILE DURING TEST............................................. 29

    APPENDIX B - STOCK VALUES DURING TEST................................................ 34

    APPENDIX C -SOURCE CODE FOR DAYTRADER ........................................... 35

    APPENDIX D - AGENT PACKAGE CLASS DIAGRAM...................................... 38

  • 8/7/2019 stock markt

    4/41

    1

    1 Introduction

    1.1 Background

    Todays stock market consists of a complex environment where supplyand demand rules over the development of shares. Simultaneously withthe development of the Internet, the range of services for stock tradershas increased. Commerce is possible in almost every marketplaceirrespective of a persons location. With an increasing availability and abetter service range, competition and complexity have grown at the stockmarkets. Complexity creates a greater need for better tools in stocktrading, and competition drives the customers desire for putting complexorders to a higher level. By a complex order is meant an order dependent

    on other conditions than price limit, quantity, and expiry time (cf. [ISE,2001]).

    A popular vision that many scientists and companies within thecomputer industry have had is that artificial software agents will be ableto support humans in a complex milieu like the one described above[Weiss, 1999]. This foresight has up to now been more theoretical thanpractical. There has been a lot of research within the area of trading agents, where one has tried to create programs that will be able to replacehumans at different kinds of auctions [Graham-Rowe, 2001].

    Today there are many definitions of software agent. In fact, it seems as if the term agent is a buzzword in the scientific as well as the businessworld [Miraftabi, 1996]. One definition of an agent is that it should bereactive and act on changes in its environment, that it should work pro-actively and take initiative to satisfy its design objectives, and have socialability to communicate with other agents [Wooldridge and Jennings,1995]. In other work, software agents have been defined as programs thatact on behalf of a human being by locating and accessing information

    [Miraftabi, 1996].Researchers at The Artificial Intelligence Laboratory at MIT have createdan experimental market with the propose of investigating the use of artificial trading agents. They have shown that computer agents using simple heuristics can accomplish what human traders do [Chan, 2000].Another study made by IBMs Institute for Advanced Commerce showsthat software agents with built-in buy and sell strategies can beat humansat a double auction. This is the same kind of auction that stock marketsuse. The agents were on average five percent more profitable then thehuman conductors [Chang, 2001].

  • 8/7/2019 stock markt

    5/41

    2

    The conditions may now be right to take stock trading one step aheadand let artificial agents act on stock markets as real traders. OM, theworld-leading provider of financial transaction technology, has started to

    look for solutions where artificial trading agents can work at real stockmarkets. Several benefits for their customers are identified using theseagents, which justify OMs ambition [Lybck and Boman, 2002]:

    Customers would be able to delegate their work to the agents

    Customers would be able to submit more complex orderswithout affecting the now running system SAXESS

    1.2 Problem

    The trading on Stockholmsbrsen is based on the computerised trading system SAXESS. This system was introduced in 1990 and moved thetrade from the floor of the Exchange to the traders own office. At eachoffice, PC-clients are usually connected to a server, which via a dedicatedline communicates with the central SAXESS system [SAXESS, 2002].

    When a trader sends an order via a terminal to the central SAXESS sys-tem, the order is time stamped, added to an order book in the core of thesystem, and then simultaneously sent out to all other traders so they canfollow the development of the market at their terminals. Bids and offersare automatically matched in the core to generate deals when price andvolume are met. This process is totally deterministic and every eventmust be traceable; the outcome must be the same from a given input[SAXESS, 2002].

    An order can not be dependent on complex conditions because thiswould lower the efficiency in the core. This fact hinders complex orders.Network congestion can also deteriorate the process and must becounteracted [Hauser and Orrhult, 2002].

    The strict requirement of determinism and security has until now keptartificial agents banned from real trading systems, because agents aremultithreaded and non-deterministic. Magnus Boman and David Lybckhave proposed [Lybck and Boman, 2002] an external system, an AgentTrade Server (ATS), which works like a link between trading agents andthe core (cf. Fig 1.1). The ATS makes it possible for each trading agent tobe executed in its own thread, while the communication with the core issynchronised. The ATS has control functions that prevent the agent fromdoing actions that can hurt the core or other agents on the ATS. Theagents working on the ATS must be able to act independently and make

  • 8/7/2019 stock markt

    6/41

    3

    their own decisions on the basis of the market data received from thecore. To make this possible the agent must have a well-defined trading strategy and be able to use the API of the ATS to interact with the trad-

    ing system. By this way, the agents will be able to meet the wish to entercomplex orders containing several conditional triggers. The agents in theATS will continuously evaluate the triggers against information from thecore. When all conditions are fulfilled the order is split up and sent to thecore.

    Fig 1.1 The ATS running with SAXESS.

    1.3 AssignmentResearchers at The Swedish Institute of Computer Science (SICS) aretogether with OM investigating the use of an ATS to complement todaystrading systems with artificial trading agents. The work of building theATS is now in progress at SICS but so far there are no agents developedto work in it. Therefore, we got the assignment from Magnus Boman,leader of the HUMLE lab at SICS, to develop a package with generalfunctions to be used by an archetypal agent in ATS execution.

    This package will contain functions that simplify development for agentATS execution and can therefore be used in later research at SICS. Thismakes it important to develop the agent package based on acceptedprogramming standards and to make it general and reusable. For thatreason the package is developed in the object-oriented programming lan-guage Java.

    1.4 PurposeWe seek to demonstrate that it is viable to develop agents with built-in

    strategies, running on an ATS, which can buy and sell stocks at a stock

    OrderbookBuy Sell

    Central SAXESS

    Member firmServer Clients

    Member firmServer Clients

    ATSAgents

  • 8/7/2019 stock markt

    7/41

    4

    market like Stockholmsbrsen. We will also investigate what commonfunctionality the agents need to accomplish this.

    1.5 HypothesisWe will show that it is possible to build agents for ATS execution. Theseagents will be small and understandable enough to give the reader, as wellas future developers, an overview of how agents like this can be built.

    1.6 Methodology

    1.6.1 Goal FulfilmentTo prove our hypothesis we have used experimental programming and

    design to implement the common functions in a Java package. The pack-age has been tested by letting a rather simple agent use it, and on thebasis of data from the ATS, run a trading strategy that make deals at anemulated version of Stockholmsbrsen.

    1.6.2 GoalsIn order to give our hypothesis quantitative meaning, we have put up fivegoals that must be fulfilled to claim that we have built a graspable ATSagent that can trade on a stock market.

    Develop an agent that can execute on the ATS (developed by SICS)without faulty behaviour

    Produce graspable agent code, consisting of no more than a fewhundred rows

    Log every action taken by each agent

    Develop an agent having the same responsibilities that a regular traderhas

    The code must be reusable, which implies that it is available and welldocumented, to simplify future development of agents for ATSexecution.

    1.6.3 Preparatory workIn the beginning of this work we searched for relevant literature con-taining information about trading agents and stock trading in general. Dueto SICSs involvement in Trading Agent Competition (TAC) someinformation was obtained from this tournament [Aurell, et al., 2002]. We

  • 8/7/2019 stock markt

    8/41

    5

    also looked for information about the current trade at Stockholmsbrsen[SAXESS, 2002] and how SAXESS works [Kohler, 2002].

    1.6.4 Work method

    Agent developmentIn the beginning of the work we were focusing on developing generalagents that could be used as examples for later research in building agentsfor stock trading. When we studied how trades were made and whichactors were involved we realised that a lot of functions were to be usedfor all stock trading agents. Therefore we decided to first find thesefunctions and implement them in a package that later on could be usedby an agent.

    Work supportThe ATS was during the work implemented at SICS by Anna Sandin.Anna has been a great help to us in designing and implementing ourpackage. During development we had contact almost every day to discussproblems and design issues. To get support and guidance we also hadfrequent meetings with Magnus Boman.

    1.7 DelimitationThis thesis is intended to demonstrate the possibility to implement soft-ware agents for ATS execution. The focus is not on developing algo-rithms for optimal buying or selling of shares with the purpose to replacestock traders. Neither will we investigate how software agents will affectstock market trading nor how the market is affected by agent trade. TheATS topic brings up many questions about security. We will only brieflydiscuss some of these issues and their possible solutions. Like security, theload problem is of great concern. We will not investigate this problembecause this work is only a proof-of-concept. If and when this theory ismade commercially available, for example by OM, the ATS will beimplemented from scratch with the security and load problemshighlighted.

  • 8/7/2019 stock markt

    9/41

    6

    2 Agent Trade ServerTo understand how agents can trade at a stock market it is important toget a comprehension for the ATS and the services it contains. Thischapter is therefore devoted to the role and implementation of the ATScreated by Anna Sandin and Magnus Boman at SICS. This implementa-tion is an experimental first version and the purpose is to prove the con-cept of an ATS.

    2.1 RoleThe reasons to use an ATS between the interaction with a trading agentand a stock market system are several. The main task for the ATS is tohave control over the agents to prevent them from doing illegal actionsthat could damage the core. An example would be illegal orders or toupload too many orders to the core. To put this responsibility on theATS instead of the core makes changes to the core unnecessary, which isrequired from OM [Lybck and Boman, 2002]. The role of the ATS istherefore to work as a complement to the core. All the complex actionsnecessary for a stock market system, in order to offer agent trading, isplaced in the ATS and the cores complexity stays at the current level.

    2.2 DesignThe ATS has a three-layered architecture that is implemented as threedifferent Java packages (cf. Fig 2.1).

    Fig 2.1 The three-layered architecture of the ATS.

    The core package contains classes and interfaces to handle communica-tion between trading agents and the ATS [Boman and Sandin, 2003].Every agent must implement the interface AgentComponent that hasmethods that for instance start and stop the ATS. The ATS supplies theservices described in the AgentContext interface [Sandin, 2002],which is an agents only view into the ATS. This interface containsmethods that can give the agent information on stocks and the possibility

    to enter orders. The reference package implements the core functionsfor the ATS itself. Functionality for handling data exchange with an

    Trading Agents

    Data sourcese.sics.ats.data

    se.sics.ats.reference

    se.sics.ats.core

  • 8/7/2019 stock markt

    10/41

    7

    external system is implemented in the data package. This is the packagethat can later be revised to connect to an actual exchange system [Bomanand Sandin, 2003]. Today the package parses data from Stockholms-

    brsens website ( http://www.stockholmsborsen.se ).

    2.3 Running Agents on the ATSWhen an agent is to be executed on the ATS it needs some preparation.First it should be packed into a jar-file. In this file it is specified whichclass is the main class, i.e. which class that implements the interfaceAgentComponent . The jar-file is loaded into the ATS via aClassLoader object. The file can either be located locally, on thesame computer as the ATS or on the Internet, at a given URL. The load-

    start-stop-program is a simple command based program that can be usedlocally and remote.

  • 8/7/2019 stock markt

    11/41

    8

    3 Requirements in Trading Agent ContextTrading agents have partly the same needs as a real stock trader. Likeregular traders, trading agents need something that keeps track of theirmoney and their stock holdings. However, when a new service, likeagents for ATS execution is introduced, there also arise new actors thatthe service must satisfy. An agent itself also has special needs to be ableto execute properly. This chapter is devoted to the surrounding of anagent and the preconditions that affect the development of trading agentsand the ATS.

    3.1 PortfolioThe fundamental requirements on trading agents can be identified bystudying the system that Swedish banks use today. Every customer thatwould like to trade needs a stock account (depkonto in Swedish) wherea customers stocks are registered [Andersson and Svensson, 2001]. Toevery stock account there is an associated bank account from whichmoney is withdrawn when stocks are bought and added when stocks aresold. Dividends are transfers to the bank account as well. Since banksstarted providing stock trading via Internet, customers can manage theirstock portfolios at a personal site on the bank site. Stock informationhandled on these sites include buy price, buy date, number of stocksbought, current stock value, and total value of portfolio. Banks takevarious fees for customers to trade. The commission rate is often 0,14 0,45 % of the trade value with a minimum charge of 50 100 Swedishkronor (cf. http://i92urbfr.island.liu.se/eisfk/arbetet.html#matris ). Some banks also take an annual commission.

    3.2 Market informationSAXESS offers traders information about stocks and their current values.

    It also sends out information about important events about the stockmarket [SAXESS]. Stockbrokers can use this information in making decisions about investments. However, stockbrokers base their decisionson a lot of other data than the ones delivered by SAXESS. An examplecould be a companys value based on analyses from annual reports[Blomquist and Leonardz, 2001].

    There are two ways for the agent to get this type of information. Oneway could be to place the information inside the agent during development. This solution is not satisfactory because the agent wouldlose its ability to react on immediate changes in its surroundings (cf.

  • 8/7/2019 stock markt

    12/41

    9

    Wooldridge and Jennings, 1995). A better way is to let the ATS supplythe agent with new information about companies and important eventson the market. The problem with this solution is to structure the

    information in a way that it gets usable for the agent. The ATS that isused in this work only delivers current stock values.

    3.3 Agent BrokerAn agent broker is a new concept introduced by Magnus Boman anddenotes a new actor in the field of stock trading [Boman and Sandin,2003]. If the use of ATS becomes a reality it is natural that some actoroutside the stock market would focus on management of trading agents.If not, it would be unmanageable to let people go direct to an ATS

    administrator to execute their agents.These brokers will handle trading agents for their customers and makethem run on the ATS. An agent broker could either handle user-devel-oped agents or user-configurable agents developed by the broker or someother agent developing company. It is possible that somebody wants atrading agent but do not have the possibility to develop its own. Anotheralternative is that agent brokers support clients in agent development.

    Agent brokers will also have the legal responsibility towards ATS owners,

    if the agent damages the ATS. This means that they have to know exactlyhow the agent works and they must verify that it is harmless beforeexecution. The broker must have control of how the agent executes. Oneway to do this is to have all their agents built on their ApplicationProgramming Interface (API), which prevents all illicit actions.

    To be able to keep up with the responsibility of having all agents activethe agent broker must, remotely, be able to view the status of all agentsand even stop the agents on demand of their owners.

    Actors trading on stock exchanges pay various fees to trade[Bernhardsson, 1996]. This will also be true for trading agents, eventhough they would presumably pay less then todays actors do. Agentbrokers will be charged for having agents running on the ATS.Consequently, like regular stockbrokers, they must charge theircustomers for managing their stocks. The difference is that agent brokersmanage stocks indirectly through the use of software agents. How theycharge their clients can differ in many ways. One approach could be totake a fee for every transaction, like a brokerage fee.

    To meet these requirements it is natural to have an object knowing therelationship between agent brokers and their agents, holding references

  • 8/7/2019 stock markt

    13/41

    10

    between them. This object can also deduct a brokerage fee and make itpossible for the physical broker to stop an agent from outside the ATS.This object must be in the same execution environment as the ATS;

    partly because the agents are running locally on the ATS and partly be-cause it could be a security problem having it outside the ATS [Bomanand Sandin, 2003]. Through this object, brokers could be notified of theiragents status and able to stop an agent via Internet.

    3.4 Keeping Track of Actions and StatusThere are several reasons why it is important to keep track of a trading agents actions and status. There are four actors that are interested in thisinformation; ATS-administrator, the agent itself, its owner and its ad-

    ministrator. These actors have different requirements of the form anddata in the log. Because of this it is natural to keep the information inXML format. This is the most widely spread standard of data and thereare easy and structured methods to transform and parse it [W3C, 2003].

    System log files are great tools for analysing system failure[Basney andLivny, 1999] . If the log files have structure and contain the right infor-mation an ATS-administrator should be able to reconstruct the eventsthat lead to the error. If an agent performs some kind of illegal action alog file could bind the action to the agent. Log files are also essential indetermining if a failure actually occurred [Basney and Livny, 1999] . Forexample if an agent owner blames the ATS administrators for some kindof error in the ATS action it is important that the error could be tracedto the ATS and not the actual agent.

    An agent needs a log for several reasons. First of all the log file could beused as a way to collect data that later could be used as basic data formaking decision strategies. There are several theories about artificial in-telligence and decision-making in stock trading. One approach is to gather

    information that could later be used together with a machine learning algorithm that uses old data to predict future prices [Hellstrm andHolmstrm, 1998] .

    The owner or the administrator of an agent must be able to follow theagents behaviour. If the agents actions are not satisfactory, the user oughtto have a way to stop the agent.

    It appears natural to put the responsibility of logging on the ATS and noton the agent because the administrator wants to be sure that the logging

    is done constantly and in the requested way [Basney and Livny, 1999] .The information could be distributed over the Internet and transformed

  • 8/7/2019 stock markt

    14/41

    11

    in the form actors require. It could then also be available for roaming users, see [Boman, et al 2002]. The work of building a notification servicefor agent owners and agent administrators is now in progress at SICS by

    Stina Nylander.If the log handling is implemented in the ATS, an agent needs a way towrite to and read from its own log. The ATS could provide a log serviceto every agent that let them log their own messages in their own format.This service could be built in a secure manner, preventing agents fromoverloading the storage area.

    3.5 Security IssuesSecurity is a big issue in the area of trading agents. The problems areseveral and span over a wide range of separated fields. This thesis onlydeals with some of these problems. It shows one way to supply some of the security services that a real ATS must support.

    The most important service from the ATS owners point of view is tokeep the ATS running and available for its customers. One threat to thisis if an agent hurt the ATS. The ATS administrator must therefore pre-vent all agents, running on the ATS, from doing illegal actions. The so-lution for this problem also manages other safety problems, like integrity

    and authentication.

    3.5.1 AvailabilityThe security model of the programming language Java provides severaltechniques to manage security problems. Every piece of programming code that is loaded into the runtime environment is attached to its sourcei.e. the path or URL where the code is saved [Oaks, 2001]. In Javas policyfiles you can specify, what code from different sources is allowed to doand not to do. Java also makes it possible for a developer to sign its code,

    which means that a digest of the code is calculated and this digest isencrypted with the developers private key. To check that a signature isvalid the encrypted digest is decrypted with the developers public keyand if this is possible the signature is verified. This signature is also at-tached to the code when loaded. Code from a particular signer can begranted specific permissions in the policy file. So if you require all agentsto be signed by some trusted part you can, in the policy file, specify whatan agent is allowed to do. This can also stop unsigned agents fromexecuting on the ATS.

  • 8/7/2019 stock markt

    15/41

    12

    Developers could sign their agents themselves, but to make it all easier toadministrate this could be a task for an agent broker for example. Publickeys are kept inside certificates. The ATS administrator must store and

    sign trusted certificates; otherwise you can not be sure that signatures arevalid [Stallings, 2000]. It would be unmanageable to keep track of all de-velopers certificates. Instead, only a few trusted parts should be allowedto sign agents, which is one more reason to have agent brokers. Thesetrusted parts must have the same security management towards theircustomers as the ATS have towards them.

    3.5.2 IntegrityAnother issue is how agent developers can be certain that no one have

    changed the preferences of the agent during transaction to the ATS. Thisproblem is already fixed if the procedures above are followed. If some-body tries to modify the code, the digest of the code would be differentand then the signature can not be verified. This will notify if something has been changed.

    3.5.3 AuthenticationATS-administrator must be able to authenticate agents and be convincedthat the agent code comes from the source that is claimed. If a signature

    can be verified it is clear that the code comes from some known source.If not, the code is unreliable.

    3.5.4 ConfidentialityHow can the agent developer be certain that no one has examined thepreferences of the agent during transaction to the ATS? To supply confi-dentiality the agent code must be encrypted. This is not done when thecode is signed. To do this the class responsible for agent loading must bedeveloped with decryption techniques. Developers or agent brokers en-

    crypt the code with the public key of the ATS before transaction. On ar-rival the code is decrypted with the private key, only known to the ATS[Stallings, 2000].

  • 8/7/2019 stock markt

    16/41

    13

    4 Service Package for Trading AgentsAs the last chapter made clear, there are many requirements on trading agents that give them a common functionality. Some of these functionsare gathered in the Java package se.sics.ats.agent , which is de-scribed in detail below. This package is to be seen as a help package todevelopers of trading agents running on the SICS ATS. It contains anumber of classes supplying functions that make it easier and faster todevelop trading agents. If used, developers can concentrate on the trading strategy. The JavaDoc for this package can be downloaded athttp://www.dsv.su.se/~mich-poi/trade_agent/ and a class diagramis available in Appendix D.

    4.1 Package DesignThe package is designed after the context that an agent works within thatwas described in the last chapter. To give an agent the same services as areal stockbroker we have created functions for handling an agents moneyand stockholdings. We have also implemented a way to handle thebroker fee. As a result, the package provides the agent with objects likean account, a stock portfolio, and an agent broker. In our implementationthese objects do not handle splits and dividends of shareholdings. Tomeet the requirements of tractability and status information we haveimplemented a log handler that handles agent events. The central part of the package is the object TradeAgent . It manages all the control func-tions and is connected to all the other objects in the package. The pack-age also implements two classes for handling complex orders and oneclass that represent an agent broker. These classes are only made forproof-of-concept and are especially made for test during development of agents.

  • 8/7/2019 stock markt

    17/41

    14

    Fig 4.1 Agent package architecture.

    4.2 se.sics.ats.agent.TradeAgent

    The TradeAgent class is the main class for the package and is designedaccording to the Facade pattern to support the package with lowcoupling [Larman, 1998]. The class is declaredabstract and will be asuper class for every subagent that wants to use the package (cf. Fig 4.1).This means that when developers create their agents, they let them ex-tend TradeAgent . That gives them all the functionality needed tocommunicate with the ATS and to keep track of their own status.

    For a developer that does not use this package it is possible to interactwith the ATS directly via the AgentContext [Sandin, 2002]. Themethods that this interface declares are implemented in theTradeAgent , which means that a subagent never needs to care aboutthe interaction to the ATS. A subagent interacts with its super class, theTradeAgent , instead. This is done almost in the same manner as viathe AgentContext interface; the same methods exist. TheTradeAgent handles all communication to the ATS. It also logs everyevent and the status using the LogHandler and updates the portfolio andthe account when changes to these are made.

    TradeAgent

    LogHandler Portfolio

    AgentBroker

    se.sics.ats.agent

    SubAgent

    se.sics.ats.reference

    se.sics.ats.core

    se.sics.ats.data

    Data source

    Account

  • 8/7/2019 stock markt

    18/41

    15

    4.2.1 Initialising and Starting SubagentsThe TradeAgent class implements the interfaces AgentComponent and Runnable . That makes it implement the initialize and

    start methods invoked by the ATS [Sandin, 2002]. These methods aredeclared as final in TradeAgent ; overwriting these methods is for-bidden.

    The start method creates a new thread that the agent executes in.When the new thread is started it calls for the run method. This is statedas an abstract method in TradeAgent and developers must imple-ment this in their subagents. In the beginning of the run method devel-opers can make their own initialisation and then start the agents strategy.

    4.2.2 Stopping SubagentsThe interface AgentComponent forces its implementation to have astop method. The TradeAgent class implements it, but it is empty.The reason is that there is no way to stop a subagents thread from thesuper agent. Instead, the subagent should override the method and haltthe thread itself. The stop method could, for example, set a boolean attribute to false that is a condition for the strategy to run.

    4.2.3 Retrieving Information about StocksThere are two ways of retrieving information about stocks. Firstly it ispossible to ask for the information by a number of get methods. For ex-ample the ask price can be fetched by the getAsk method. Secondlystock data can be collected by subscribing for the information via thesubscribe method in TradeAgent . By doing this the subagent willbe notified every time the stock property changes. It is also possible tounsubscribe information that is no longer relevant.

    4.2.4 Entering OrdersWhen an agent needs to place an order to the system it uses the Order object and the interface OrderListener [Sandin, 2002]. An order iscreated by calling the method createOrder that returns the Order object. This object is then sent to the enterOrder method that alsotakes an OrderListener as argument.

    An OrderListener is an object that implements the methodsorderCancelled and orderClosed . When an order is either

    closed or cancelled by the ATS the portfolio and the account are updated

  • 8/7/2019 stock markt

    19/41

    16

    and log entries for the event is added. Then the subagentsOrderListener is called for.

    4.3 se.sics.ats.agent.AccountThe Account object represents an agents asset and works like a bankaccount. The TradeAgent is able to set the value of the Account andadd as well as remove value from it. However, the subagent can onlycheck how much value it holds. When a subagent enters a buy order theTradeAgent check with the Account that there is money to coverthe order. From the beginning the value is set to 10 000 by the final variable INIT_VALUE . In a real version of this package the Account should be a middleware communicating with the client money account

    system at the broker that specify what currency the asset is in and whereinterest is added.

    4.4 se.sics.ats.agent.PortfolioThe Portfolio is a collection class for the stocks that an agent owns.It holds ShareHolding objects, which in its turn keep track of astocks id or symbol, its quantity and what it did cost when bought.

    Every time an order is closed the TradeAgent object updates the

    Portfolio ; stocks are added and removed if it is a buy order, respec-tively, sell order. If stocks that already exist are added and the cost pricediffers between the new stocks and the existing, an average of the twoprices is calculated. When a subagent enters a sell order viaTradeAgent , it checks with the Portfolio that the agent actuallyhas the stocks it is trying to sell and that it has the right quantity.

    A subagent can not change its shareholdings by itself. It can only get in-formation about them. For simplicity the portfolio is empty from the be-ginning. However, a real implementation of this class will need to con-nect to a middleware for receiving information on client holdings.

    4.5 se.sics.ats.agent.LogHandlerDuring the work process, the log handling was first placed inside theagent package. Later on it was also implemented in the ATS. This im-plementation was not satisfactory because the agent was unable to accessits own log in the ATS. For that reason the log handling were kept insidethe agent. However, this is not the most favourable solution.

    The LogHandler class intend to keep track of an agents action andstatus. Every action that takes place in the TradeAgent is logged into a

  • 8/7/2019 stock markt

    20/41

    17

    file in XML-format. When an order is closed the status of the portfolioand the account is written into the log. The date and time, when the log where made, is attach to every log element (cf. Fig 4.2). The log makes it

    possible to follow an agents action from when it was started until itstermination.

    Fig 4.2. Example from a status file.

    4.5.1 Log methodsThe LogHandler writes data in two separate files, one with the agentsactions and status and one with all errors. The following methods log events in the status.xml file:

    logGetEvent Log when an agent fetches stock data via a get methodin TradeAgent .

    logSubscribeEvent Log when an agent subscribes or unsub-

    scribes information about a stock.logPropertyChangedEvent Log when a propertyChange object is triggered.

    logOrderEvent Log every event that is connected to an Order object.

    LogStatus Log value of the portfolio and the account.

    The following methods log errors in the error.xml file:

    logException Logs a Java Exception.logError Logs aString object as an error.

    4.6 se.sics.ats.agent.AgentBrokerBecause of the different financial arrangements possible for the adoptionof the agent broker concept, it is not implemented in the first version of the ATS (version 1.0). Due to this, some agent broker functionality isimplemented in the agent package instead and put in the classAgentBroker . However, this is only temporary and not optimal. TheAgentBroker class in this package only handle brokerage fee.

  • 8/7/2019 stock markt

    21/41

    18

    4.6.1 Deducting Brokerage FeeWhen an order is closed, the method orderClosed inMyOrderListener in TradeAgent calls the method

    getBrokerageFee in AgentBroker with the orders value as pa-rameter. This method calculates the fee and returns it. In theAgentBroker, two final variables can be set; MINIMUM_BROKERAGE_FEEand BROKERAGE_FEE, which affect the calculation.These can differ between agent brokers.

    4.7 se.sics.ats.agent.ComplexOrderThe ComplexOrder object and the Evaluator interface are createdto give developers a mechanism for easier implementation of complexorders. It breaks down the complexity of trading strategies to simplifydevelopment of these. Developers only need to specify which conditionsmust be true and which orders to enter if they are.

    This is only one simple way to demonstrate how the mechanism of com-plex order could be handled. To put this further, a later version couldhave a standardised and structured way to set the conditions. The task toevaluate these should be done by the ATS, which ought to provide thecomplex order service instead of this package.

    4.7.1 Creating and Starting Complex OrderTo a ComplexOrder object it is possible to add several Order objectsthat is created via the TradeAgent . The developer states the conditionsthat must be fulfilled in the eval method in the Evaluator object.When a ComplexOrder object is started it creates a thread that callsthe eval method by a given interval. In this implementation the mini-mum interval is one second. If the eval method returns true the Order objects are send to the ATS via enterOrder in TradeAgent . AComplexOrder object is self-going and manage it self when started.

    4.8 Access-Level ControlTo prevent users of the package from abusing its functions and using it inanother way then intended, different access levels are put to its objectsand its methods.

    The TradeAgent is the class that connect the subagent to the ATS andthe other classes in the package. TradeAgent holds references to the

    classes; LogHandler , Portfolio , Account , and AgentBroker .These references are all declared as protected to prevent non-sub

  • 8/7/2019 stock markt

    22/41

    19

    objects outside the package to access the classes. The references are alsodeclared as final, which make it impossible for the subagent tochange these references to point to modified classes.

    The classes inside the package have some method declared aspackage-private , only accessible for theTradeAgent . This is mainly methodsthat change data in the objects. The methods that are supposed to beaccessed by the subagents are declared as public and are only get-methods. The reference to the thread is stated as protected and asubagent can use the thread to control its own execution. The referenceto AgentContext is made private to stop subagents to interactwith ATS direct.

  • 8/7/2019 stock markt

    23/41

    20

    5 ResultThis chapter contains a description of how we, with the help of a simpleagent, tested the package described in the last chapter. The test was car-ried out by letting the agent execute on the ATS. The result of theagents action can be seen in Appendix A and the stocks developmentduring that time is shown in Appendix B.

    5.1 Test Preparations

    5.1.1 ATS PreparationsWhen agents run on the ATS it is hard to predict their actions becausethey totally depend upon the stock development during runtime. Instead

    of letting our agent run against real-time stock rates during the test, wecreated an XML file that the ATS used to update its order book.

    The only package that was changed in the ATS was the data package thatinstead of using the class StockQuoteParser used aStockUpdater that parsed the XML-files for ask and bid prices. Everyfive seconds, the parser updated its order book with the next value in thefiles. When the end of the XML file was reached the updater used thelast value in the log file. During test, the brokerage fee, calculated by

    AgentBroker , was set to zero.

    5.1.2 DayTrader AgentThe DayTrader is a simple agent that looks at a stock rate and tries tobuy the stock when the prices starts to increase and sells the stock assoon as the price decreases (cf. Fig 5.1). The source code for theDayTrader can be seen in Appendix C.

    At start-up DayTrader looks up the current sell price for the specifiedshares. It then subscribes information from the ATS to follow changes inthe ask price. When a change is triggered the agent either sells or buys theshare and then updates the initial price to the latest value to see how theshare did develop at the next coming change.

    If the share starts to fall the agent tries to sell this share holding. Theagent looks up the current bid price and puts a sell order at that price. Bydoing this the share will be sold if the bid price does not decreases beforethe order reaches the core.

    If the price starts to increase, the agent tries to buy ten blocks of the

    share. It looks up the current sell price and then places a new bid order.

  • 8/7/2019 stock markt

    24/41

    21

    The agent only holds ten shares at a time. If the price increases and theagent already holds stocks of that type in the portfolio it does not buy anynew ones.

    The agent is not developed to be optimal in the sense of making as muchmoney as possible but instead be an aid for testing the package.

    5.1.3 Stock Development During TestWe created our own stock during test that we called the SICS stock.Figure 5.1 show its development during test. For the first five updates thevalue of the stock does not change so the agent will have time to start upand start a subscription for the ask price. After that the ask price rises andis during update 11-13 at a value of 109. It then falls back to a minimum

    ask price at 96 in update 25. In the last five updates the values rise againand end at their origin. The values that where used are also available in

    Appendix B.

    Fig 5.1 The DayTrader is intended to buy a stock when the price starts to increase at

    the sixth update. It should then try to sell the stock when the prices start to fall at the14 th update. At 26 th it should buy again.

    5.2 Test Result

    5.2.1 Agent PerformanceDuring the test the agent created a log file over its actions. The log filecan be seen in Appendix A. At start up the agent had 10 000 at the ac-count and no stocks in the portfolio. It then started with getting the askprice for the SICS stock that at the time had the value of 100. To follow

    the changes in the ask price the agent added a subscription for the SICSstocks ask price. Every time the ask price was changed the agent logged

    Stock development

    85

    90

    95

    100

    105

    110

    115

    1 4 710

    13

    16

    19

    22

    25

    28

    Update

    Value

    Ask PriceBid Price

  • 8/7/2019 stock markt

    25/41

    22

    an event of type: property_changed . When the ask price started to rise inupdate six the DayTrader created an order containing ten SICS sharesfor the cost of 101. The order was entered into the ATS and the agent got

    a notification almost directly that the order was closed. Every time theportfolio or the account is changed a new status tag is logged. The statusshows that it was invoked when the order was closed. The portfoliocontained 10 shares of SICS. The shares were bought at a value of 101 andwere at the time worth 1000 together.

    To calculate the portfolio value the TradeAgent ask for the currentbid price. This was logged just before the status. The value of the stockincreased to 109 and for every change the DayTrader logged aproperty_changed event. When the ask price started to fall again theDayTrader sold its possessions. In order to do this it first asked theATS for the current bid price. This price where then used in the creationof the order that contained all the shares. The order where entered to theATS and closed. The status shows that the account had a value of 10 060and that the portfolio was empty.

    The ask prices started to decrease at update 14 and the agent logsproperty_changed event that shows the reduction. When the ask pricesstarted to increase again at update 26 the DayTrader once again placed

    a bid order on the ATS, the order was closed and the status was logged.The last status shows that the agents account has a value of 9090 and theportfolio contains ten shares of SICS with a total value of 960.

    5.2.2 Comments About the TestThe test shows that the package can create a log file that shows an agentsaction during execution. The package also handled the account and theportfolio for the agent properly. This was shown in the status tags in thelog file.

    In this test the agent performed relatively well. It ended up with more as-sets than it started with. However this is all depending on the develop-ment of the stock. If a brokerage fee had been taken for every transactionthe result would have been less impressive.

    If the prices are oscillating with a small interval the agent with a strategylike DayTrader would probably lose a lot of money instead, because itwould sell stocks for less then the investment price.

    There is a risk that a sell order does not close because a stock decreasesfaster then the agent is able to enter the order. If this happens the agent

  • 8/7/2019 stock markt

    26/41

    23

    would probably be stuck with stocks for a long time that it could not sell.One idea with the ATS is that the agent will have a faster interactionthen other traders. This would maybe avoid the above problem. Another

    solution would be to enter an order under the bid price.

  • 8/7/2019 stock markt

    27/41

    24

    6 ConclusionBy implementing a trading agent package, as well as a trading agent thatuses its functions, we have proved our hypothesis, and our stated goalshave been fulfilled. We have shown that an agent that runs on the ATS,and uses the agent package, can be kept small. Our agent consisted of only 190 rows of source code. During tests, the agent worked as predictedand without a faulty behaviour.

    We have studied the context of stock trading agents and showed whatkind of functions that are common between trading agents and importantfor them to work properly. The Account keeps track of an agents assetand restricts overdraft. This object may in the future be connected to a

    bank. The Portfolio is used to handle agent stockholdings and theLogHandle r could be used for the agent to save important information.The thesis also points out requirements from actors in a trading agentsmilieu. An agent owner or an agent administrator needs to follow anagents actions and keep informed about how it performs. The ATS ad-ministrator needs to follow every agents actions for error tracking. TheLogHandler satisfies these requirements by logging all actions taken byan agent.

    We argue that the implementation of the agent package demonstrateshow common functions for trading agents could be collected and that it ispossible to meet the requirements that the surroundings have. The pack-age could be used in future research by using the code anddocumentation available at http://www.dsv.su.se/~mich-poi/-trade_agent/

    It is difficult to know when a sufficient result has been reached whengoing for proof-of-concept using experimental programming. It is not likebasic research with fixed goals that you can tick off, which is a weaknessin our work. We still believe that this methodology is the best methodfor this work. Moreover, the test made of the agent at the end of thisthesis is more scientific and can be reproduced. This concept may notbe proved or accepted until commercial interest is put to it or it isgenerally established. We have worked in an experimental environmentwhere there has been a parallel development of the ATS and the agents.This has made the work process less effective, but at the same time it hasenabled us to assist in developing the ATS itself, which has been useful toSICS.

    The implementation of the ATS and the agents in this thesis is experi-mental and demonstrates their possible part at stock markets of the fu-

  • 8/7/2019 stock markt

    28/41

    25

    ture. But for this to be a reality there is still a lot of work to be done if implementing a secure system. The possibility to do this can be discernedin this thesis and the key issue in future development of an agent trading

    system will be security. We believe that a lot of security responsibilitywill be put to the future agent brokers. If the security services that Chap-ter 3.3 describes are implemented in the interaction between the ATSand the agent broker, it is possible to offer customers integrity,authentication and confidentiality. An agent broker can also handle theregulations of investment by providing their customers a common APIthat capsulate control functions.

    There is also another hindrance. The service needs to be delivered to themarket and a well trusted infrastructure around the concept must be

    built. It is important to make dealers realise that the use of trading agentsis an alternative to traditional trading. It is a prerequisite that the systemis accepted by the market before it could be used, and that dealers findconfidence in the system.

    We believe that the use of these services could become a reality and incommon use, if the conditions are right, and that the benefits are great.How this will affect the behaviour of the market, if this is true, is anopen question.

  • 8/7/2019 stock markt

    29/41

    26

    AcknowledgementsWe would like to thank Magnus Boman, our examiner and supervisor atSICS, for his support and feedback during this thesis. Our thanks also goto Anna Sandin for her ideas and for valuable discussions in implementing the agent package. We appreciate the design meeting with JoakimEriksson and Niklas Finne at SICS. We would like to thank David Lybckat OM as well, for constructive feedback and corrections. We are alsograteful for the work done by Johan Kummeneje at DSV in reviewing the thesis.

  • 8/7/2019 stock markt

    30/41

    27

    References[Andersson and Svensson, 2001] Lennart Andersson & Ulf Svensson,Aktieaffrer, Bjrn Lundn Information AB, 2001

    [Aurell, et al.] Aurell, E.; Boman, M.; Carlsson, M.; Eriksson, J.; Finne, N.;Janson, S.; Kreuger, P. & Rasmusson, L.: A trading agent built onconstraint programming, Proc Computing in Economics and Finance(CEF 2002), Aix-en-Provence, June 2002.

    [Basney and Livny, 1999] Deploying a High Throughput Computing ClusterJim Basney and Miron Livny, Department of Computer SciencesUniversity of Wisconsin-Madison Wisconsin, USAhttp://www.cs.wisc.edu/condor/doc/hpcc-chapter.ps

    [Bernhardsson, 1996] Jonas Bernhardsson, Trading Guiden, Fischer & Co,Stockholm, 1996

    [Blomquist and Leonardz, 2001] Anders Blomquist, Bjrn Leonardz,rsredovisning, Liber Ekonomi, Malm, 2001

    [Boman et al., 2002] Magnus Boman, Markus Bylund, Mats Danielson,Fredrik Espinoza, David Lybck. Trading Agents for Roaming Users.Swedish Institute of Computer Science (SICS) AB, 2002

    [Boman and Sandin, 2003] Magnus Boman, Anna Sandin. Implementing Agent Trade Servers. In preparation

    [Chan, 2000] Nicholas Tung Chan, Artificial Markets and AdaptiveAgents.Artificial Intelligence Laboratory, Massachusetts Institue Of Technology,Cambridge, Massachusetts 02139, 2000http://www.ai.mit.edu/research/abstracts/abstracts2000/pdf/z-NChan.pdf , 2002-09-10

    [Chang, 2001] Kenneth Chang. New Age Bidding: Against Computers,Humans Usually Lose. The New York Times, January 2001.

    [Graham-Rowe, 2001] Duncan Graham-Rowe. Robots beat humancommodity traders.http://www.newscientist.com/news/news.jsp?id=ns99991131 , 2001-08-30.

    [Hauser and Orrhult, 2002] Vincent Hauser, Joakim Orrhult, NetworkMonitoring for Networking Agents, Department of Computer andSystems Sciences, Stockholm University / Royal Institute of Technology,January 2002.

    [Hellstrm and Holmstrm, 1998] Tomas Hellstrm, KennethHolmstrm, Prediction the Stock Market, Center of Mathematical

  • 8/7/2019 stock markt

    31/41

    28

    Modeling (CMM), Department of Mathematical and Physics, MlardalenUniversity. August 9 1998.http://citeseer.nj.nec.com/20821.html

    [ISE, 2001] International Securities Exchange (ISE),http://www.iseoptions.com/legal/pdf/ric/2001/RIC-2001-15$Complex_Orders$20011024.pdf , 2003-03-09

    [Larman, 1998] Craig Larman. Applying UML and Patterns, Prentice Hall,Upple Saddle River, 1998.

    [Lybck and Boman, 2002] David Lybck, Magnus Boman, Agent TradeServers in Financial Exchange Systems, Swedish Institute of ComputerScience (SICS) AB, 2002

    [Miraftabi, 1996] Agents on the Loose: An Overview of AgentTechnologies, Ramin Miraftab, Department of Computer Science,University of Joensuu, 1996http://www.cs.joensuu.fi/~khakala/ITS2000/agents/index.html

    [Sandin, 2002] Anna Sandin, ATS Java doc, SICS,http://www.sics.se/~sandin/ats/doc/index.html , 2003-01-22

    [Weiss, 1999] Intelligent Agents, Michael Wooldridge. Chapter 1 in:Multiagent Systems - A Modern Approach to Distributed ArtificialIntelligence, Gerhard Weiss (ed.), pp. 27 - 78, MIT Press 1999.

    [SAXESS, 2002]http://www.stockholmsborsen.se/handelsinfo/index.asp?lank=1&lang=swe , 2003-02-25

    [Kohler, 2002] Jonas Kohler. SAXESS Trade Technical Reference, version34.2. OM Technology AB, 2002-07-23

    [Stallings, 2000] William Stallings, Network Security Essentials:Applications and Standards, Prentice Hall, New Jersey, 2000.

    [Oaks, 2001] Scott Oaks, Java Security, OReilly & Associates, Sebastopol,

    2001.[W3C, 2003]http://www.w3.org/XML/ , 2003-02-10

    [Wooldridge and Jennings, 1995] M. Wooldridge and N. R. Jennings,Intelligent agents: theory and practice, Knowledge Engineering Review,1995.

  • 8/7/2019 stock markt

    32/41

    29

    Appendix A - Agent Log File During Test

  • 8/7/2019 stock markt

    33/41

    30

  • 8/7/2019 stock markt

    34/41

    31

  • 8/7/2019 stock markt

    35/41

    32

  • 8/7/2019 stock markt

    36/41

    33

  • 8/7/2019 stock markt

    37/41

    34

    Appendix B - Stock Values During Test

    Update Ask Price Bid Price1 100 992 100 993 100 994 100 995 100 996 101 1007 102 1018 104 1039 105 10410 106 10511 109 108

    12 109 10813 109 10814 108 10715 108 10716 108 10717 108 10718 107 10619 106 10520 103 10221 101 10022 99 98

    23 98 9724 97 9625 96 9526 97 9627 98 9728 99 9829 100 9930 100 99

  • 8/7/2019 stock markt

    38/41

    35

    Appendix C -Source Code For DayTrader

    package daytrader;

    import se.sics.ats.core.*;import se.sics.ats.agent.*;

    import java.util.*;

    /**

    * This class is a simple daytrader that subscribes information from theats

    * and act according to the stocks development.

    */

    public class DaytraderAgent extends TradeAgent implements OrderListener,PropertyChangedListener {

    private HashMap stockValues = new HashMap();private HashMap processingOrders = new HashMap();

    private final String stock = "SICS";

    /**

    * Main processing method for the DayTrader object

    */

    public void run() {

    //Retrives the first stockvalue for SICS with getAsk

    stockValues.put(stock, new Double(getAsk(stock)));

    //Starts a subscription for changes in stock ask price

    subscribe(this, Constants.SP_ASK, stock);

    }//run

    /**

    * Every time the stockpropery changes, this method is called. Its apart of

    * PropertyChangeListener. It checks if the price has gone up and thencalls

    * the buy method if that is the case. However if the price has fallenthe sell

    * method is called.

    */

    public void propertyChanged(Object newValue, int property, Stringsymbol) {

    Double aValue = (Double) stockValues.get(symbol);

    double lastValue = aValue.doubleValue();

    Double dvalue = (Double) newValue;

    double currentValue = dvalue.doubleValue();

    stockValues.put(symbol, newValue);

    //Control for investment

    if (currentValue > lastValue) {

  • 8/7/2019 stock markt

    39/41

    36

    if (!holdsStock(symbol)) {

    processingOrders.put(symbol, new Double(currentValue));

    buy(currentValue, symbol);

    }

    }

    //Controll for selling

    if (currentValue < lastValue) {

    if (holdsStock(symbol)) {

    double bid_value = getBid(stock);

    processingOrders.put(symbol, new Double(bid_value));

    sell(bid_value, symbol);

    }

    }

    } // propertyChanged

    /**

    * Enter a bid order

    */

    private void buy(double currentBid, String symbol) {

    try {

    Order order = createOrder(symbol, 1, currentBid, 10);

    enterOrder(order, this);

    } catch (ExceededAccountException e) {

    log.logException(e);

    } catch (ExceededStockQuantityException e) {log.logException(e);

    } catch (NoSuchStockException e) {

    log.logException(e);

    }

    }//buy

    /**

    * Enter an ask order

    */

    private void sell(double currentBid, String symbol) {

    try {

    Order order = createOrder(symbol, 0, currentBid, 10);

    enterOrder(order, this);

    } catch (ExceededAccountException e) {

    log.logException(e);

    } catch (ExceededStockQuantityException e) {

    log.logException(e);

    } catch (NoSuchStockException e) {

    log.logException(e);

    }

    }//sell

  • 8/7/2019 stock markt

    40/41

    37

    /**

    * Method that is called when an order is closed. The symbol is

    * removed from precessingOrders

    */public void orderClosed(Order order) {

    processingOrders.remove(order.getSymbol());

    }//orderClosed

    /**

    * Method that is called when an order is cancelled. The symbol isremoved

    * from precessingOrders

    */

    public void orderCancelled(Order order) {

    processingOrders.remove(order.getSymbol());}//orderCancelled

    /**

    * Checks if the portfolio contains the symbol

    */

    private boolean holdsStock(String symbol) {

    String[] holdings = portfolio.getSymbols();

    for (int i = 0; i < holdings.length; i++) {

    if(holdings[i].equals(symbol)|| processingOrders.containsKey(stock))

    return true;

    }

    return false;

    }//holdsStock

    }//class

  • 8/7/2019 stock markt

    41/41

    Appendix D - Agent Package Class Diagram

    ExceededAccountException

    ExceededAccountException()

    (from agent)

    Evaluator

    ev al()

    (from agent)

    ExceededStockQuantity Exception

    ExceededStockQuantity Exception()

    (from agent)

    NoSuchStockException

    NoSuchStockException()

    (from agent)

    LogHandler

    ENDTAG : String = ""STARTTAG : String = ""STATUS_FILE_NAME : String = "status.xml"ERROR_FILE_NAME : String = "error.xml"

    FILE_PATH : String = "agent_log"

    LogHandler()setPath()logGetEv ent()logSubscribeEvent()logProperty ChangedEvent()logOrderEvent( )logStatus()logException()logError()createLogFile()createVariable()getDateAndTimeString()getEventStartTag()log()

    (from agent)

    AgentBroker

    BROKERAGE_FEE : double = 0.00MINIMUM_BROKERAGE_FEE : double = 0.00

    getBrokerageFee()

    (from agent)

    Account

    INIT_VALUE : int = 10000v alue : double

    Account()getValue()setValue()

    addValue()remov eValue()

    (from agent)

    ComplexOrder

    running : boolean = fals eev alTime : int = 1000

    ComplexOrder()ComplexOrder()addOrder()start()run()stop()getOrders()getEvaluator()

    (from agent)

    Shareholding

    shareId : Stringquantity : intcostPrice : double

    Shareholding()getShareId()getQuantity ()getCostPrice()setQuantity()setCostPrice()toString()

    (from agent)Portf olio

    Portf olio()getHolding()getSym bols()getQuantity ()getCostPrice()getCurrentValue()getTotalValue()toString()addShareholding()remov eShareholding()

    (from agent)

    ListenerRef erence

    property : intsy mbol : String

    ListenerRef erence()getListener()getProperty ()getSymbol()

    (from agent)ListenerHolder

    ListenerHolder()addListener()removeListener()

    (from agent)

    Day traderAgent

    run()property Changed()buy()sell()orderClosed()orderCancelled()holdsStock()

    (from daytrader) AgentContext

    getVolume()getAmount()

    getBid()getAsk()

    getChangeInPercent()getChangeInSEK()

    getLast()getHigh()getLow()

    getName()subscribe()

    unsubscribe()createOrder()enterOrder()deleteOrder()

    getActiv eOrders()log()

    (from core)

    TradeAgent

    initialize()start()stop()marketOpened()marketClosed()run()

    getVolume()getAmount()getBid()getAsk()getChangeInPercent()getChangeInSEK()getLast()getHigh()getLow()getName()createOrder()enterOrder()deleteOrder()unsubscribe()subscribe()

    (from agent)

    -agentContext