Sunday 8 October 2017

Gebäude Automatisiert Handels System C ++ Net


Gebäudeautomatisierte Handelssysteme. Mit einer Einführung in Visual C 2005 Transkription 2 Building Automated Trading Systems mit einer Einführung in Visual C 2005 3 Die Financial Market Technology Serie Serie Editor Ben Van Vliet Die Financial Market Technology Series ist eine Partnerschaft zwischen Elsevier, Inc. und dem Institut für Markttechnologie (I4mt), um hochmoderne Bücher zu veröffentlichen, die Themen betreffend die Integration von Technologie mit den Finanzmärkten veröffentlichen, darunter: automatisierte Handels-, Gebäudehandels - und Investitionssysteme, operative Fragen im Backoffice, Clearing und Settlement sowie Compliance - und Governance-Themen Zur technologie Das Ziel der Serie ist es, das Verständnis und die Kompetenz mit der Technologie in der Finanzbranche zu fördern, indem sie qualitativ hochwertige Bücher über die neuesten Forschungs - und Praxisbereiche für Fachleute an den Finanzmärkten veröffentlichen. Serienredakteur: Ben Van Vliet ist Dozent und Associate Director des M. Sc. In Financial Markets Programm an der Stuart Graduate School of Business, Illinois Institute of Technology. In diesem Programm unterrichtet er Graduiertenkurse in quantitativer Finanzierung und automatisierte Handelssystementwicklung mit Visual Basic, SQL, XML, ISO C und Visual C und UML. Er ist auch ein Miterfinder von TraderDNA, ein Echtzeit-Trading Performance Evaluation Softwarepaket, sowie ein Director bei TraderDNA LLC. Er dient auch als stellvertretender Vorsitzender des Instituts für Markttechnologie (i4mt), einer gemeinnützigen Organisation, die Bildungsprogramme an Finanzmärkten und Technologie anbietet, wo er auch den Markttechnischen Ausschuss für das Certified Trading System Developer (CTSD) Programm leitet. Bitte beachten Sie weitere Informationen. Herr Van Vliet berät sich auch in der Finanzindustrie. Er ist Autor von Building Automated Trading Systems (Academic Press, 2007) und Co-Autor von Modeling Financial Markets (McGraw-Hill 2004). Wir begrüßen Vorschläge für Bücher für die Serie. Bitte gehen Sie zu wo Sie einen Link finden, um uns Ihren Vorschlag zu schicken. 4 Building Automated Trading Systems mit einer Einführung in Visual C 2005 Benjamin Van Vliet AMSTERDAM BOSTON HEIDELBERG LONDON NEW YORK OXFORD PARIS SAN DIEGO SAN FRANCISCO SINGAPUR SYDNEY TOKYO Akademische Presse ist ein Abdruck von Elsevier 5 Academic Press ist ein Abdruck von Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, USA 525 B Straße, Suite 1900, San Diego, Kalifornien. USA 84 Theobald s Road, London WC1X 8RR, UK Dieses Buch ist auf säurefreiem Papier gedruckt. Copyright 2007, Elsevier Inc. Alle Rechte vorbehalten. Kein Teil dieser Publikation darf ohne schriftliche Genehmigung des Herausgebers in irgendeiner Form oder auf irgendeine Weise elektronisch oder mechanisch, einschließlich Fotokopie, Aufzeichnung oder irgendein Informationsspeicher - und Abrufsystem, vervielfältigt oder übertragen werden. Berechtigungen können direkt von Elsevier s Science amp Technology Rights Department in Oxford, UK gesucht werden: Telefon: (44). Fax: (44). Sie können Ihre Anfrage auch online über die Elsevier-Homepage (elsevier) abschließen, indem Sie Support amp Kontakt dann Copyright und Berechtigung auswählen und dann Berechtigungen erhalten. Bibliothek des Kongresses Katalogisierung-in-Publikation Daten Van Vliet, Benjamin Gebäude automatisierte Handelssysteme. Mit einer Einführung in Visual C 2005 Benjamin Van Vliet. P. cm. Enthält bibliographische referenzen und index. ISBN (Alk. Papier) 1. Elektronischer Handel von Wertpapieren 2. Finanzierung mathematische Modelle. 3. Microsoft Visual C Microsoft. I. Titel. HG V dc Britische Bibliothek Katalogisierung-in-Publikationsdaten Ein Katalogdatensatz für dieses Buch ist bei der British Library erhältlich. ISBN 13: ISBN 10: Informationen zu allen Publikationen der Akademischen Presse finden Sie auf unserer Website unter Druck in den Vereinigten Staaten von Amerika 6 Inhalt Danksagungen xiii KAPITEL 1 Einleitung ISO C Struktur dieses Buches 2 Abschnitt I: Einführung in Visual C 2005 KAPITEL 2 Die Framework MS Visual Studio 2005 Projektstruktur Was ist CCLI Warum Visual C Der VC Compiler Was ist mit der Geschwindigkeit Der Framework Beispielcode: MessageBoxExample Beispielcode: StringConcatExample Beispielcode: DebugExample Versioning Summary 14 KAPITEL 3 Tracking Referenzen Beispielcode: TrackingReferenceExample Beispielcode: TemplateFunctionExample Managed Handle Beispielcode: Ref TypeExample Summary 17 v 7 vi Inhalt KAPITEL 4 Klassen und Objekte Abstraktion Kapselung Vererbung Polymorphismus Speicherverwaltung in NET-Typen Nicht verwaltete Typen Mixed Assemblies Zusammenfassung 23 KAPITEL 5 Referenztypen Beispielcode: Ref TypeExample Löschen und entsorgen Finalisieren Beispielcode: FinalizeExample Stack Semantics Für Ref-Typen Nullrev-Referenz Dies ist wichtig Zusammenfassung 31 KAPITEL 6 Werttypen Beispielcode: ValueTypesExample Beispielcode: PassingValueTypesExample Summary 36 KAPITEL 7 Nicht verwaltete Objekte Beispielcode: UnmanagedObjectExample Summary 39 KAPITEL 8 Komposition Beispielcode: CompositionExample Beispielcode: UnmanagedCompositionExample Beispielcode: ManagedCompositionExample Summary 48 KAPITEL 9 Eigenschaften Beispielcode: EigenschaftenExample Summary 50 KAPITEL 10 Strukturen und Enumerationen Beispielcode: ValueStructureExample Beispielcode: ReferenceStructureExample Beispielcode: EnumsExample Summary 53 8 Inhalt vii KAPITEL 11 Vererbungszugriffsmodi Objektklasse Abstrakt und versiegelte Klassen Beispielcode: VererbungExample Interfaces Sample Code: InterfaceExample Runtime Callable Wrapper Zusammenfassung 60 KAPITEL 12 Konvertieren und Gießen Konvertieren von Beispielcode: ConvertExample Static Casting Beispielcode: StaticCastExample Dynamic Casting Beispielcode: DynamicCastExample Safe Casting Beispielcode: SafeCastExample Summary 65 KAPITEL 13 Operator Überladen Beispielcode: OpOverloadExample Summary 69 KAPITEL 14 Delegierte und Ereignisse Delegierte Beispielcode: DelegatesExample Multicasting Beispielcode: MulticastExample Events Beispielcode: EventExample Wrapper Beispielcode: WrapperExample Asynchrone Methode ruft Beispielcode auf: AsynchEventExample Summary 82 KAPITEL 15 Arrays Beispielcode: ManagedArrayExample Beispielcode: PassingArraysExample Summary 85 vii 9 viii Inhalt KAPITEL 16 Ausgabesatzcode: FormsTimerExample Beispielcode: ThreadingTimerExample Beispielcode: TimerTimerExample Summary 98 KAPITEL 18 Input - und Output-Streams FileStream. Für eine grössere Darstellung klicken Sie auf das Bild. Für eine grössere Darstellung klicken Sie auf das Bild Klasse StreamWriter Klasse Datei - und Verzeichnisklassen Anwendungsklasse FileMode Enumeration Beispielcode: StreamWriterExample Beispielcode: StreamReaderExample Summary 101 KAPITEL 19 Exception Handling Beispielcode: AusnahmenExample Catching Nicht verwaltete C-Typen Zusammenfassung 105 KAPITEL 20 Sammlungen Beispielcode: HashtableExample Sortierte Liste Klasse Beispielcode: SortedListExample Thread Sicherheits-Generika Beispielcode: LinkedListExample Beispielcode: GenericsExample Summary 112 KAPITEL 21 STLSTL Beispielcode: STLEXample Beispielcode: STLEXample Summary 114 10 Inhalt ix KAPITEL 22 DataSets Beispielcode: DataSetExample Zeilen, DataRowCollections und DataRows Zusammenfassung 117 KAPITEL 23 Anbindung an Datenbanken Datenbankverbindung DataAdapter Beispielcode: ADOExample Aufzählung durch alle Daten in einem DataSet Verwendung von Excel als Datenquelle Schreiben von XML aus einem DataSet Aktualisieren einer Datenbank mit Änderungen in einem Dataset Abrufen von Daten mit einer DataReader-Zusammenfassung 124 KAPITEL 24 Strukturierte Abfragesprache Datenmanipulationssprache Aktualisieren einer Datenbank Mit Änderungen in einer DataSet-Daten-Defi - nition Language Summary 140 KAPITEL 25 XML Gut geformte XML-Dokumente Gültige XML-Dokumente XML-Schema-Dokumente Parser Beispielcode: Traders. xsd Beispielcode: XmlWriterExample Beispielcode: XmlReaderExample Summary 146 KAPITEL 26 Finanzinformationen Exchange Protocol XML Protocols In Finanzmärkte Übersicht der FIX-Zusammenfassung 151 KAPITEL 27 Serialisierung SerialisierungBeispiel Zusammenfassung 154 KAPITEL 28 Windows Services Beispielcode: WindowsServiceExample Summary 159 11 x Inhalt KAPITEL 29 Setup - und Installationspakete Beispielcode: InstallationBeispiel Zusammenfassung 162 Abschnitt II: Gleichzeitigkeit KAPITEL 30 Threading Threading Namespace Sample Code : ThreadExample Beispielcode: ThreadAbortExample Thread Priority Beispielcode: ThreadPriorityExample ThreadState Enumeration ThreadPool Klasse Beispielcode: ThreadPoolExample Aktualisieren von Formularen aus anderen Threads Beispielcode: FormUpdateExample Thread Safety Summary 175 KAPITEL 31 Synchronisationsklassen Beispielcode: SynchronisierenExample Mutex Klasse Beispiel Code: MutexExample Semaphore Class Sample Code: SemaphoreExample Monitor Class Beispielcode: Monitor Zusammenfassung 182 KAPITEL 32 Sockets Beispielcode: SynchronousServerExample Beispielcode: SynchronousClientExample Summary 189 Abschnitt III: Interoperabilität und Konnektivität KAPITEL 33 Marshaling Marschallklasse Beispielcode: StringToCharArrayExample Summary 194 KAPITEL 34 Interieur und Pinning Pointers Beispielcode: InteriorPointerExample Pinning Pointers Beispielcode: PinningExample Summary 198 12 Inhalt xi KAPITEL 35 Anschließen an verwaltete DLLs Beispiel Code: DLLExample Summary 201 KAPITEL 36 Verbinden mit Component Object Model (COM) DLLs mit COM Interop Beispielcode: MyCOMLibrary Beispielcode: Verwenden vonCOMDLLExample Summary 207 KAPITEL 37 Verbinden mit C-DLLs mit Plattform-Aufrufdiensten Aufruf von C-Style-Funktionen Beispielcode: MyWin32Library Beispielcode: Verwenden vonWin32DLLExample Erstellen von Objekten Beispielcode: MyWin32ClassLibrary Beispielcode: Verwenden vonWin32ClassExample CallingConventionEnumeration Zusammenfassung 216 KAPITEL 38 Anschließen an Excel Beispielcode: ControllingExcelExample Beispielcode: ExcelChartExample Summary 221 KAPITEL 39 Verbindung zu TraderAPI TraderAPI Übersicht FillObj InstrObjClass InstrNotifyClass OrderObj OrderProfi leclass OrderSetClass Beispielcode: TraderAPIConnectionExample Summary 230 KAPITEL 40 Verbinden mit XTAPI Beispielcode: XTAPIConnectionExample Summary 233 13 xii Inhalt Abschnitt IV: Automatisierte Handelssysteme KAPITEL 41 Building Trading Systems Kaufen vs. Build Data Mapping Geschwindigkeit der Entwicklung Zehn Dinge, die die Geschwindigkeit eines Trading-Systems beeinflussen Getting It Right Logic Lecks Zehn Dinge, die die Profitabilität eines Trading-Systems beeinflussen Zusammenfassung 245 KAPITEL 42 KV Trading-System-Entwicklungsmethodik Die Geld-Dokument-Forschung und Dokument-Berechnungen Zurück Test Implementieren Portfolio verwalten Und Risikosumme 257 KAPITEL 43 Automatisierte Handelssystemklassen Instrumentenklasse Auftragsklasse Auftragsbuchhalterung Tick Tick oder Bar Collection Bar Systemmanager Grafische Benutzeroberfläche Zusammenfassung 265 KAPITEL 44 Einzelne Threaded, Technische Analyse System Beispielcode: TechincalSystemExample Summary 277 KAPITEL 45 ProducerConsumer Design Pattern Beispielcode: ProducerConsumerExample Summary 287 KAPITEL 46 Multithreaded, Statistical Arbitrage System Beispielcode: SpreaderExample Summary Fazit 304 14 Danksagungen Dieses Buch begann als Klassenzahl für einen Kurs, den ich am Illinois Institute of Technology unterrichtete, der Advanced Object Oriented Programming for Financial Markets genannt wird. In dieser Klasse decken wir automatisiertes Trading-System-Design und - Entwicklung mit Microsoft Visual C. Wenn ich begann, diesen Kurs vor einigen Jahren zu unterrichten, konnte ich kein Buch finden, das alle notwendigen Themen für den Aufbau von Echtzeit-, automatisierten Handelssystemen und so, Als Ergebnis versucht dieses Buch, genau das zu tun, dass es Programm - und technologiebezogene Themen für die Entwicklung von Handelsauswahl, Auftragsrouting, Auftragsmanagement und Positionsmanagementalgorithmen zusammenbringt. Ich hoffe, dass mehr Schulen Kurse über automatisiertes Handelssystemdesign in der Zukunft anbieten werden und dass dieses Buch in ihrer Unterweisung hilfreich sein wird. Darüber hinaus ist dieses Buch ein Grundstein für das CTSD Certified Trading System Developer Programm des Instituts für Markttechnologie (i4mt. org). Dies ist ein neues Zertifizierungsprogramm, das aus drei Prüfungen besteht, einer in quantitativen Finanzierungen, einer in der Wertpapier - und Derivathandelsstrategie und einer in der ISO-CC-Programmierung und der Markttechnologie. Dieses rigorose Selbststudienprogramm soll die heute in der Finanzbranche geforderten Skillsets zusammenbringen. Kandidaten, die die CTSD-Bezeichnung erreichen, werden talentierte Menschen sein. Wie man sich vorstellen kann, muss für viele Freunde, Familien und Kollegen zusätzlicher Kredit für die Fertigstellung dieses Projektes gegeben werden: vor allem meiner Frau Julia Mark McCracken, Dr. Andrew Kumiega, Andrew Acosta, Sagy Mintz, Jason Malkin, Larissa J. Miller, Derek Walther, Niraj Chokshi, Julian Mulla, Mike Hermanson, David Norman, Dr. Deborah Cernauskas, Dr. Joe Wojkowski, Pamela Reardon, Edward Wang, Alex Deitz, Andrew Robinson und alle meine Kollegen im IIT Center Für Finanzmärkte Russell Wojcik, Dr. Michael Gorham, Keith Black, Dr. Michael Ong, Dr. John Bilson, Dr. Michael Kelly und Jodi Houlihan. Auch ich möchte mich bei den vielen Studenten bedanken, die meinen Kurs genommen haben und alle wertvolles Feedback gegeben haben. Ohne ihre Hilfe und die Hilfe von vielen anderen wäre dieses Buch niemals fertiggestellt worden. Xiii 15 xiv Danksagungen Dieses Buch ist für Menschen mit Kenntnis von ISO C oder evtl. Java, oder COM geschrieben. Für Finanz-Ingenieure und aufstrebende Finanz-Ingenieure mit einem allgemeinen Programmierung Hintergrund, wird dieses Buch eine eingehende Diskussion über übergeordnete Programmierung Konzepte wie Event-Handling, Interoperabilität, Daten-Feed-Konnektivität und Parallelität. Für erfahrene C-Programmierer, können Sie feststellen, dass dieses Buch bietet eine gute Einführung in die Verwendung von C innerhalb des Framework. Was auch immer der Fall ist, ich hoffe, Sie lernen daraus und sind begeistert, tiefer in das Thema der automatisierten Handelssystementwicklung einzutauchen. Bitte geben Sie mir ein Feedback, das Sie haben. Ich verspreche, meine Website zu aktualisieren, regelmäßig mit Korrekturen an Errata und weiteren Beispielen. 16 KAPITEL 1 Einleitung Automatisierte (oder algorithmische) Handelssysteme bestehen aus vielen Teilen, sowohl Hardware - als auch Software-Clients, Servern, Netzwerken, Datenbanken, Rechenmaschinen, Anwendungsprogrammierschnittstellen, Echtzeit-Datenfeeds und grafischen Benutzeroberflächen. Allerdings ist die Geschäftslogik der Handelssysteme, die aus Handelsauswahlalgorithmen, Auftragsmanagement und Positionsmanagementlogik besteht, in Software enthalten, und dieses Buch beschäftigt sich mit der Kapselung von Handelssystem Geschäftslogik in Software, die den Marktfluss steuert Daten. (Es gibt kein Quant in diesem Buch.) Ein automatisiertes Handelssystem besteht aus den Regeln für den Eintritt in und Ausstieg aus einer Position oder Positionen und die Technologie, sowohl Hardware als auch Software, verwendet, um sie geschehen zu lassen. Diese Regeln sind eine Reihe von logischen oder mathematischen Operationen, die auf qualitativer, technischer oder quantitativer Forschung basieren können. Wenn wir ein automatisiertes System bauen wollen, das Trades auf elektronischen Börsen durchführt, müssen wir lernen, wie man mit Daten, sowohl Echtzeit-Marktdaten als auch historischen Daten, in Code arbeiten kann. Immerhin ist die Daten der Lebensnerv der elektronischen Märkte, so David Norman in seinem Buch Professional Electronic Trading. Das ist genau das, worum es in diesem Buch geht, mit Visual C, um Finanzmarktdaten zu verwalten (und es gibt viel davon) in Handelssystemanwendungen. Im Allgemeinen umfasst dieses Buch drei Dinge: 1. Verwalten von Daten im Speicher. 2. Daten speichern und aus Datenbanken abrufen. 3. Daten kommunizieren Die Front-Office-Programmierung an den Finanzmärkten beschäftigt sich weitgehend mit der Anbindung an Datenbanken, Echtzeit-Datenfeeds, Auftragsabwicklungsplattformen, Quantbibliotheken, Optimierungsmaschinen, Charting-Software, Reportgenerationsmotoren, Legacy-Technologien und Excel, um nur einige zu nennen. Um Echtzeit - und historische Daten erfolgreich zu verwalten, müssen wir verstehen: 1. Event-getriebene Architektur. 2. Gleichzeitigkeit. 3. Konnektivität und Interoperabilität. 1 17 2 KAPITEL 1 Einleitung Während dieses Buch Dutzende von wichtigen technologischen Fragen, die Sie beim Aufbau von realen automatisierten Handelssystemen vorstellen werden, zeigt es Ihnen nicht, wie Sie ein profitables Handelssystem aufbauen können. (Es ist doch wichtig zu erkennen, dass technologische Überlegenheit ein großer Wettbewerbsvorteil sein kann.) Es gibt vier Disziplinen, die in die automatisierte Handelssystementwicklung Informatik, quantitative Finanzierung, Handelsstrategie und Qualitätsmanagement gehen und dies ist ein Informatikbuch. Entwicklung und Erprobung von Handelsauswahl - und Risikomanagementmethoden sind Themen für andere Bücher. Dieses Buch behandelt die Grundlagen dessen, was ein Finanz-Ingenieur über die Programmierung in Objekten, SQL, Multithreading, Interoperabilität, Messaging, Order Selektionsalgorithmen und Auftragsmanagement-Techniken wissen sollte. In diesem Text habe ich versucht, marktgetriebene, berufsrelevante Informationen einzubeziehen. Die heutigen Arbeitgeber in den Finanzmärkten fordern die Bereitschaftsbereitschaft. Wenn Sie einen Job in der Handels - und Geldmanagementbranche bekommen wollen, der immer mehr jeden Tag von automatisierten Systemen angetrieben wird, müssen Sie einen wettbewerbsfähigen Kenntnis der Programmierung haben. Sie sollten erkennen, dass dieses Buch aber ein Überblick ist. Es wird dir nicht alles beibringen. Technologie als Thema ist offensichtlich viel zu groß, um in einem Buch zu decken. Sogar verengt es auf VC für Handel Systementwicklung ist noch viel zu weit. Auf den Seiten werde ich Ihnen einige wichtige Ideen vorstellen, versuchen Sie, Sie in die richtige Richtung zu stellen, und hoffentlich am Ende begeistern Sie zusätzliche Untersuchungen zum Thema automatisierte Handelssystementwicklung. Von dort muss der sorgfältige Finanzingenieur weiter auf seine eigene ISO C untersuchen. Dieses Buch behandelt die Programmierungsaspekte der Handelssystementwicklung und geht davon aus, dass Sie mit ISO C Programmierkonzepten vertraut sind, einschließlich Zeiger, Funktionen, Objekte und der Standardvorlage Bibliotheksstruktur dieses Buches Automatisierte Handelssysteme finden ihre reinste Form in hochfrequenten Strategien, bei denen die Geschwindigkeit der Berechnung und Ausführung der Wettbewerbsvorteil ist. Andere Systeme, in denen Millisekunden nicht unbedingt von wesentlicher Bedeutung sind, können vollautomatisch oder teilweise automatisiert werden. Dieser Text konzentriert sich auf die Einführung von Programmier - und Designkonzepten für höherfrequente Systeme. Die Diskussion aller alternativen technologischen Konzepte des Trading-Systemdesigns und der Präsentation eines kompletten Handelssystems geht über den Rahmen eines Buches hinaus. Die in diesem Buch vorgestellten Handelssysteme sind drastisch vereinfacht, um gängige Programmier - und Gestaltungskonzepte zu veranschaulichen. Dieses Buch ist in vier Abschnitte unterteilt. Der erste Abschnitt konzentriert sich ausschließlich auf eine Einführung in Visual C-Typen und Programmiertechniken. Der zweite Abschnitt konzentriert sich auf Multithreading. Die dritte konzentriert sich auf Interoperabilität und Konnektivität und die vierte auf Objekte, Designmuster und architektonische Konzepte für die automatisierte Handelssystementwicklung. Am Ende, einfach das Lesen dieses Buches wird Ihnen nicht ein Experte. Um das Material in diesem Buch wirklich zu lernen, solltest du auch die vorgelegten Codebeispiele bearbeiten. Nur wenn du dich in den Prozess einbeziehst und darüber hinaus darüber hinausgehst, wirst du Verständnis und Intuition gewinnen. Es ist eine harte Arbeit, aber es wird sich auszahlen. 18 ABSCHNITT I Einführung in Visual C 2005 19 Diese Seite wurde absichtlich freigelassen 20 KAPITEL 2 Das Framework 2.1. MS Visual Studio 2005 Projektstruktur In MS Visual Studio 2005 wird Ihre Softwareanwendung als Lösung bezeichnet und eine Lösung kann aus einem oder mehreren Projekten bestehen, wobei jedes Projekt möglicherweise in einer anderen Visual Studio Sprache sein könnte. Im Laufe dieses Buches werde ich Lösungen vorstellen, die zum größten Teil in MS Visual C für verwaltete oder Anwendungen aus Gründen entwickelt wurden, die ich in Kürze erklären werde. Beachten Sie jedoch, dass Visual C keine neue Programmiersprache ist, sondern eine umfassende Entwicklungsumgebung, die eine erhöhte Unterstützung für viele C-Projekttypen bietet, einschließlich: Active Template Library (ATL) Projekte. MS Foundation Classes (MFC) Projekte. Oder verwaltete Konsole, Windows - oder DLL-Projekte. Win32-Konsolenprojekte für ISO-C-Projekte. Win32-API-Projekte und DLLs. Infolgedessen ist Visual C für oder verwaltete Projekte nur eine von mehreren C-Sprachen, die in Visual Studio 2005 angeboten werden, und dies ist eines der Dinge, die das neue VC abgesehen von den anderen in der Familie setzt, bietet es im Wesentlichen fünf unabhängige C-Sprachen in ein Paket. Also, wenn du weiterhin MFC-Anwendungen machen möchtest, kannst du das auch so machen. In der Tat wurde die Unterstützung für MFC und ATL tatsächlich in VS verbessert In früheren Versionen von Visual Studio wurde die Erweiterung zum Namen hinzugefügt, um es von früheren Versionen wie Visual Basic 6.0 zu unterscheiden. Mit dem Aufkommen von VS 2005 ist die Erweiterung des Namens in der Regel ausgeschlossen und wir können sie als VB, C und Visual C verweisen. Was ist CCLI CCLI (Common Language Infrastructure) ist eine Ableitung von C. Nach Stanley Lippman von Microsoft: 5 21 6 KAPITEL 2 Die Framework-CLI bezieht sich auf die Common Language Infrastructure, eine mehrstufige Architektur, die ein dynamisches Komponentenprogrammiermodell unterstützt. In vielerlei Hinsicht stellt dies eine vollständige Umkehrung des C-Objektmodells dar. Eine Laufzeit-Software-Schicht, das virtuelle Ausführungssystem, läuft zwischen dem Programm und dem zugrundeliegenden Betriebssystem. Der Zugang zu der zugrunde liegenden Maschine ist ziemlich eingeschränkt. Der Zugriff auf die im ausführenden Programm aktiven Typen und die zugehörige Programminfrastruktur wird sowohl als Entdeckung als auch als Aufbau unterstützt. Der Schrägstrich () stellt eine Bindung zwischen C und der CLI dar. Eine erste Annäherung einer Antwort auf das, was CCLI ist, ist, dass es eine Bindung des statischen C-Objektmodells an das dynamische Komponentenobjektmodell der CLI ist. Kurz gesagt, es ist, wie Sie die Programmierung mit C statt C oder Visual Basic. Wie C und die CLI selbst, CCLI befindet sich im Rahmen der European Computer Manufacturers Association (ECMA) und schließlich unter ISO. Die Common Language Runtime (CLR) ist die Microsoft-Version der CLI, die für das Windows-Betriebssystem spezifisch ist. Ähnlich ist Visual C die Implementierung von CCLI. Als zweite Annäherung an eine Antwort integriert CCLI das Programmiermodell in C genauso wie bei Bell Laboratories, wir integrierten die generische Programmierung mit Vorlagen innerhalb des damals vorhandenen C. In diesen beiden Fällen sind Ihre Investitionen in eine bestehende C-Codebasis Und in deinem vorhandenen C-Fachwissen sind erhalten. Dies war eine wesentliche Grundvoraussetzung für das Design von CCLI. Im Laufe dieses Buches werde ich einfach auf Microsoft-Implementierung von CCLI als Visual C zu verweisen. Für Mr. Lippman s vollständigen Artikel, gehen Sie zu msdnmagissues0600purecdefault. aspx Warum Visual C Also warum Visual C Was sind die Vorteile von verwalteten oder C-Anwendungen einfach Legte und in den Worten eines Vizepräsidenten eines großen Trading-Software-Anbieters hier in Chicago, NET ist die Zukunft. Am wichtigsten ist, dass das Framework viele, viele Klassen enthält, die bei der Entwicklung von Handelssystemen helfen, wie wir sehen werden. Darüber hinaus enthält VC im Vergleich zu den anderen Sprachen viel größere Unterstützung für die Interoperabilität zwischen verwaltetem und nicht verwaltetem Code. Darüber hinaus ist auf den Finanzmärkten die Interoperabilität entscheidend. In VC haben wir eine präzise Kontrolle über verwaltete und nicht verwaltete Heap - und Stack-Speicherzuweisung und verwalteten und nicht verwalteten Code und alle können nahtlos in demselben Projekt existieren. Damit können wir unsere bestehenden C-Applikationen, Funktionalitäten und Objekte schnell und einfach in neue Applikationen integrieren. Dies gilt insbesondere für COM-Anwendungen, die in der Finanzindustrie stark genutzt werden und nicht verwaltet werden. Darüber hinaus, wenn Sie Bibliotheken von Objekten oder finanziellen Funktionen in native C geschrieben haben, VC mit seiner umfangreichen verwalteten verwalteten Interop-Unterstützung geben Ihnen enorme Kontrolle. Alternativ, wenn Sie vorhandene C-Anwendungen haben, die Sie umwandeln möchten, wird VC Ihnen die Werkzeuge zur Verfügung stellen, die die anderen Sprachen t und don t haben. Schließlich, während die 2005 Version der STL (bekannt als STL) ist noch nicht ganz verfügbar, wird es bald und Konvertierung native STL-abhängigen Code wird ein Kinderspiel. 22 2.6. DER RAHMEN Der VC-Compiler Hier sind ein paar Dinge, die man sich an den VC-Compiler erinnern kann. Der VC-Compiler, C1.exe, verwendet die Erweiterung. c für C-only-Kompilierung und. cpp für C und C. Auch die Standard-Header benötigen keine Erweiterung von. h, da Microsoft seine eigenen Versionen dieser Dateien enthalten hat Der std namespace Weiterhin zeigt ein Projekt s Eigenschaftenfenster alle Compiler-Einstellungen für CC an, einschließlich der Linker - und Build-Events. Microsoft s Cl. exe Compiler implementiert ANSI C und ISO C Standards und ist 98 C kompatibel nach Microsoft. Der Compiler bietet Lösungskonfigurationen für Debug-Builds und Release Builds. Mit einem Debug-Build können wir mit unserem Code während der Laufzeit interagieren. Das ist eine große Hilfe Allerdings werden keine Optimierungen gemacht und dazu nutzen wir den Release-Build, der schneller, optimierter Code generiert. Der Compiler erlaubt uns, nativen C-Code in unsere Projekte zu integrieren und erstmals in Microsoft Intermediate Language (MSIL) kompilieren. Dann wird die MSIL durch den Just In Time (JIT) Compiler in nativen Code umgewandelt. Mit JIT sind einige Operationen schneller als native C, während andere langsamer sein werden. Infolgedessen gibt es Kompromisse zwischen Entwicklungsgeschwindigkeit und Ausführungsgeschwindigkeit. Allerdings gibt es Dinge, die wir tun können, um die Kosten für bestimmte Operationen zu minimieren. Mit dem VC-Compiler und dem JIT können Sie den schnellstmöglichen Code mit den verfügbaren Compiler-Optionen erstellen. Wenn Sie ernsthaft über Geschwindigkeit sind, nehmen Sie sich Zeit, um weitere Microsoft s VC Compiler zu untersuchen Was über Geschwindigkeit Geschwindigkeit ist natürlich wichtig, natürlich. Für eine eingehende Diskussion über Geschwindigkeitsüberlegungen in verwaltetem Code verweise ich Sie auf einige ausgezeichnete Artikel in der MSDN Library (msdn. microsoft. comlibrary): Ein Baker s Dutzend: Dreizehn Dinge, die Sie vor dem Portieren Ihrer Visual C Programme wissen sollten Zu Visual Studio 2005 von Stanley Lippman. Best Practices für das Schreiben effizienter und zuverlässiger Code mit CCLI von Kenny Kerr. C: Die leistungsstärkste Sprache für Framework Programming von Kenny Kerr. Schreiben schnellere Managed Code: Wissen, was die Dinge von Jan Gray kostet. Schreiben von leistungsstarken Managed Applications: Ein Primer von Gregor Noriskin (enthält einen Überblick über den CLR Profiler). Tipps zur Verbesserung des zeitkritischen Codes. Optimierung Best Practices im Visual C-Bereich Das Framework Wenn wir verwaltete Visual C-Anwendungen erstellen, werden unsere Programme im Framework entwickelt, kompiliert und ausgeführt. Der Rahmen besteht aus drei Teilen: 23 8 KAPITEL 2 Der Rahmen 1. Common Language Runtime (CLR). 2. Klassenbibliotheken 3. ASP. ASP ist die Web-Entwicklungsplattform von Microsoft für den Aufbau von Unternehmens-Webanwendungen, die zu langsam für die Echtzeit-, Finanzmarktanwendung laufen, und so werden wir keine Zeit damit verbringen, sie zu untersuchen. Vielmehr werden wir unsere Zeit damit verbringen, über die gemeinsame Sprachlaufzeit und die Klassenbibliotheken zu lernen und wie wir sie nutzen können, um Finanzanwendungen zu erstellen, die möglicherweise auf mehreren Betriebssystemen laufen können, nicht nur Windows, einschließlich Unix, Linux und Mac Common Language Runtime CLR steuert die Codeausführung innerhalb des Frameworks und stellt basierte Programme mit Sprachüberwachung, Sicherheit, dynamischem Speicherverwalten und Debugging von Diensten zur Verfügung. Weiterhin steuert die CLR, was wir verwalteten Code nennen, der im verwalteten Heap ausgeführt wird. Das heißt, der verwaltete Haufen wird vom Framework und nicht vom Betriebssystem gesteuert. Nicht verwalteter Code (oder Nicht-Code) wird jedoch vom Betriebssystem gesteuert. Die CLR bietet auch eine dynamische Speicherverwaltung, indem sie einen Garbage Collector verwendet, um die Zuweisung und Freigabe des Speicherplatzes zu verwalten, wodurch die häufigsten Speicherverlustprobleme, die häufig in der Software auftreten, beseitigt werden. Die CLR-Zuweisung des Speichers auf dem verwalteten Heap ist, es stellt sich heraus, tatsächlich schneller als die nicht verwaltete Heap-Zuweisung und fast so schnell wie die Stack-Speicherzuweisung, da sie zusammenhängende Speicherplätze durch einfaches Inkrementieren eines Zeigers zuteilt. In, der Compiler kompiliert verwalteten Quellcode zuerst in MSIL. Bevor Code ausgeführt wird, wird MSIL von einem Just-in-Time (JIT) Compiler konvertiert, der für Ihre Computerarchitektur spezifisch ist. JIT konvertiert MSIL in Maschinensprache oder nativen Code, zur Laufzeit Garbage Collection Der Garbage Collector bestimmt die beste Zeit, um eine Sammlung von nicht referenzierten Objekten durchzuführen. Der Garbage Collector gibt den Speicherplatz frei, der auf Objekte zugewiesen wird, auf die in der Applikation nicht mehr verwiesen wird (oder darauf hingewiesen wird). Das Framework hält eine Liste der aktiven Referenzen, die der JIT-Compiler und die CLR beibehalten. Der Garbage Collector verwendet diese Liste, um alle Referenzen der Anwendung zu untersuchen. Objekte, die nicht auf der Liste sind, werden als nicht erreichbar betrachtet und der Speicherplatz wird freigegeben. Infolgedessen untersucht der Garbage Collector den verwalteten Haufen und findet Raumblöcke, die von nicht referenzierten Objekten besetzt sind. Gleichzeitig werden referenzierte Speicherplätze verdichtet und verschoben und die notwendigen Aktualisierungen der Zeigerreferenzen erfolgen. Es ist wichtig zu beachten, dass der Müllsammler Objekte ohne Erinnerung in Erinnerung richten wird. Dies hat wichtige Konsequenzen später auf Assemblies Assemblies bilden die grundlegenden Bausteine ​​für das Framework und jede Anwendung, die in ihm entwickelt. Assemblies existieren am häufigsten als ausführbare Dateien oder dynamische Link-Bibliotheksdateien und enthalten Gruppen von Klassen, die eine logische Funktionseinheit bilden. 24 2.7 SAMPLE CODE: MESSAGEBOXEXAMPLE 9 Assemblies enthalten Informationen über Inhalt, Versionierung und Abhängigkeiten, so dass die Anwendungen, die wir mit Visual C erstellen, nicht auf Registry-Werte angewiesen sind, um ordnungsgemäß zu funktionieren. Da Registry nicht erforderlich ist, können wir Visual C-Anwendungen generell installieren, indem wir einfach das Verzeichnis der ausführbaren Dateien auf den Zielcomputer kopieren. Namespaces Namespaces organisieren die Tausende von Klassen in den Bibliotheken, verhindern Mehrdeutigkeit und vereinfachen Referenzen, wie wir sehen werden. (VC-Programme, die wir schreiben, enthalten oftmals mehrere Namespaces.) Im Systemnamensraum steht der Root-Namespace und enthält primitive Datentypen und fundamentale Klassen wie Object (von denen alle Objekte abgeleitet werden), String, Exception und den Müll Sammlerklasse, GC. Die Visual Studio-Dokumentation (die Hilfedateien) enthält eine Framework-Klassenbibliothek Referenzseite, die eine umfassende Liste der Namespaces mit Beschreibungen enthält. Da alle Programmierung inhaltlich von den in diesen Namespaces enthaltenen Objekten abhängt, können Sie sich einige Zeit damit verbringen, sich mit den verschiedenen Namespaces und den Arten von Objekten vertraut zu machen, die sie enthalten. Vollständig qualifizierte Namen Wenn Sie Bibliotheken verwenden, können wir Objekte, die an externen Orten definiert sind, instanziieren Solange wir einen Verweis auf die Versammlung hinzufügen und dann den vollqualifizierten Namen für die Klasse in unserem Code verwenden. Ein vollständig qualifizierter Name ist eine Klassenreferenz, die mit seinem Namensraumnamen versehen ist. Here is an example of how to create an object using the fully qualified class name for a class in another namespace: System::Windows::Forms::MessageBox::Show( Hello, world ) Fully qualified names prevent naming conflicts because the compiler can always determine which class is being used. However, the names themselves can get long and cumbersome. As a way around this, we can use the using namespace statement. The following code uses this shortcut: using namespace System::Windows::Forms MessageBox::Show( Hello, world ) As you will see, within our own user-defined namespaces, we can define modules, interfaces, classes, delegates, enumerations, structures, and even other namespaces Sample Code: MessageBoxExample Let s create a new Visual C program that will illustrate the use of namespaces. Step 1. Start Visual Studio Step 2. In the File menu item, click on New and Project The New Project window will appear (Figure 2-1). Step 3. Highlight Visual C Projects in the Projects Types pane and CLR Console Application in the templates pane. Also, be sure to give your project a name and a location. OK klicken. 25 10 CHAPTER 2 The Framework When your solution is ready, you should see the Solution Explorer window on the righthand side of your screen. If not, click on the icon as shown. The Solution Explorer will allow you to navigate through the files that comprise your solution (Figure 2-2). Because our Console Application does not by default allow for a user interface, we need to add a reference to the System::Windows::Forms namespace. The Forms namespace contains the class definitions for Windows forms. FIGURE 2-1 FIGURE 2-2 26 2.8. SAMPLE CODE: STRINGCONCATEXAMPLE 11 Step 4. In the Solution Explorer window, right click on the project name and select References The MessageBoxExample Property Pages window will appear. Click on the Add New Reference icon. In the list of components, navigate down to System::Windows::Forms. Click Select and then click OK. The References directory in the Property Pages window should now list System. Windows::Forms. Step 5. In the MessageBoxExample. cpp code window, type the following: MessageBoxExample. cpp. main project file. include stdafx. h using namespace System using namespace System::Windows::Forms int main(arrayltsystem::stringgtargs) Console::WriteLine(L Hello, World ) MessageBox::Show( Hello, World ) return 0 Step 6. Compile the program by clicking the Build menu item and Build MessageBox Example. Run the program by clicking the Debug menu item and Start Without Debugging. Notice again that the MessageBox class definition is located within the System. Windows::Forms namespace. (Using the optional L before a string constant designates the native, wide character type wchart.) 2.8. Sample Code: StringConcatExample Concatenating strings for display can be done in many ways as can formatting numbers for display using the String class or the ToString method as shown. The StringBuilder class also comes in handy. In order to use the StringBuilder class, use the System::Text namespace as shown. include stdafx. h using namespace System using namespace System::Text int main(arrayltsystem::stringgt args) String mlang C int my 2005 27 12 CHAPTER 2 The Framework Console::WriteLine( This is Visual 0 1, mlang, my) Console::WriteLine(String::Concat( This is Visual, mlang. my)) Console::WriteLine( This is Visual mlang my) Notice the formatting possible using the ToString method. Console::WriteLine(Math::PI. ToString( . )) StringBuilder mbuilder gcnew StringBuilder( This is Visual C ) mbuilder-gtappend(my) Console::WriteLine(mBuilder) return 0 2.9. Sample Code: DebugExample Here is another example that illustrates the use of the Debug class and the Output Window. Step 1. Start Visual Studio 2005 as before. This time highlight Visual C Projects in the Projects Types pane and Windows Forms Application in the templates pane. Again, be sure to give your project a name and a location. Step 2. The Form1.h Design Window should appear. Double click on your Form1 and Visual Studio will automatically generate an event handler for the Form1 load event. This function will run when Form1 loads. Add the following code to the method: private: System::Void Form1Load(System::Object sender, System::EventArgs e) Debug::WriteLine( Hello, World ) The output of this program does not show a message box, but rather will print the output through the Debug class, which is defined in the System::Diagnostics namespace, which we will need to add. Step 3. In the Form1.h code window, be sure to add: using namespace System::Diagnostics Here is what the completed, Form1 code window should look like. pragma once namespace DebugExample using namespace System using namespace System::ComponentModel using namespace System::Collections 28 2.9. SAMPLE CODE: DEBUGEXAMPLE 13 using namespace System::Windows::Forms using namespace System::Data using namespace System::Drawing using namespace System::Diagnostics public ref class Form1. public System::Windows::Forms::Form public: Form1(void) InitializeComponent() protected: Form1() if (components) delete components private: System::ComponentModel::Container components Windows Forms Designer generate code private: System::Void Form1Load(System::Object sender, System::EventArgs e) Debug::WriteLine( Hello, World ) Step 4. Build your application and then run it using the blue Start icon on your task bar. To view the output, view the aptly named Output window (Figure 2-3). If you cannot find it, click on the Other Windows icon. We often use the static methods of the Debug class to print program information and to check program logic. Use of the Debug class does not impact the performance of the application. 29 14 CHAPTER 2 The Framework FIGURE Versioning The Framework provides help with project versioning. In a project s AssemblyInfo. cpp file, we can set the version number easily. Version information for an assembly consists of the following four values: Major Version Minor Version Build Number Revision You can specify all the value or you can default the Revision and Build Numbers by using the as shown next: assembly:assemblyversionattribute( 1.0. ) Summary This chapter reviewed the VC solution structure, how assemblies and namespaces are organized, how the CLR controls managed memory, and the garbage collector. Also, we developed some simple solutions to illustrate use of message boxes, the debug window, the console window, and string concatenation. Finally, we looked at some of the reasons why VC is such a great language for developing automated trading systems. 30 CHAPTER 3 Tracking References Because a referenced type may be moved around at runtime by the common language runtime (CLR), the native C amp cannot be used to reference an object on the garbage collected heap. In VC the CLR will update the new tracking reference with the new location. A tracking reference can refer to a managed or native object, a data member, or a storage location, but cannot be a member of a class. Also, by using a tracking reference in a template function, we can ensure that the function can be called with native, value, or reference types Sample Code: TrackingReferenceExample This example shows that the tracking reference replaces the native C amp reference. As you will see, however, we will still use the native amp on occasion. include stdafx. h using namespace System int main(arrayltsystem::string gt args) int x 3 int ampa x int b x Console::WriteLine(x) Console::WriteLine(a) Console::WriteLine(b) return 0 15 31 16 CHAPTER 3 Tracking References 3.2. Sample Code: TemplateFunctionExample For now, do not worry about the distinction between a ref class, a native class, and a value class. This is not a fully working code example as the class definitions are left out. Here, simply note the use of the tracking reference operator in the template function. include stdafx. h include MyRefClass. h include MyNativeClass. h include MyValueClass. h using namespace System templatelttypename Tgt void function1(t) int main(arrayltsystem::string gt args) MyRefClass mrefobj(3) MyNativeClass mnativeobj(4) MyValueClass mvalueobj(5) Managed Heap Stack Stack function1(mrefobj) function1(mnativeobj) function1(mvalueobj) return 0 templatelt typename T gt void function1(t manyobj) Console::WriteLine(mAnyObj. getValue()) VC supports templates and also things called generics, which we will look at in a later chapter Managed Handle Because a referenced object may be moved around at runtime by the common language runtime, the native C cannot be used to point on an object on the garbage collected, or managed, heap. In VC, replaces to declare a handle to an object on the managed heap and then uses gcnew rather than the traditional new keyword to create instances. Object member selection through this handle uses the arrow notation. 32 3.5. SUMMARY Sample Code: RefTypeExample This example will be explained in more detail in a later chapter. For now, just take note of the new notation, which declares a handle to a managed object. A handle, for our purposes, operates in a fashion logically equivalent to a C pointer. include stdafx. h include MyClass. h using namespace System int main(arrayltsystem::string gt args) MyClass mobj gcnew MyClass(2) Console::WriteLine(mObj-gtgetValue()) return 0 3.5. Summary This chapter looked at the new syntax for managed references, , and managed pointers, . We will be using managed references thoughout the book, so be sure you are comfortable with them before you proceed. 33 This page intentionally left blank 34 CHAPTER 4 Classes and Objects This book uses objects and object-oriented programming (OOP) to control program flow. OOP enables us to organize large programs logically and allows us to perform very large and complex tasks with fewer lines of code. Before we begin, let s review classes and objects. An object is an instance of a class and, in addition to our own classes, Microsoft s Framework gives us hundreds of ready-made classes in the namespaces. We can create instances of these classes as reference types and as such they will be managed by the common language runtime (CLR). Visual C is an object-oriented programming language. As such we will make use of classes, which have data and functionality together in their respective definitions. Classes have member variables or data members that store data and functionalities, or behaviors, held in procedures known as methods or member functions. As we will see, classes may also have events associated with them. The button click is an example of an event. In a working program, different objects work together, or talk to each other, through their respective public interfaces the collection of public methods exposed by an individual object. That is to say, private data within an object, which is not accessible from the outside world, is available to the outside programming environment only via the object s public interface. A major benefit of OOP is that because the data and methods encapsulated in classes are so closely tied together, we do not need to pass member variables back and forth as inputs to the member functions. Rather, member functions can access member variables directly within their definitions. If you are not overly familiar with classes, Table 4-1 shows elements that make up a class. In Visual C, we can create our own user-defined classes and create objects based on them. For example, we could create a class called Instrument. In a program, a real-life, tradable instrument would be an object, i. e. an instance of the Instrument class. Let s briefly review the four main concepts of object-oriented programming: abstraction, encapsulation, inheritance, and polymorphism Abstraction Abstraction is the process of creating an abstract model of a real-world object or thing. The process consists of taking the attributes, or properties, and functionalities, or methods, of a thing and turning them into logical pieces of data and functionality. 19 35 20 CHAPTER 4 Classes and Objects TABLE 4-1 Member Variables Variables Objects Properties Property Member Functions Methods Constructor Finalization Events Event Description Simple, primitive data. Other types classes, structures, interfaces, enums, etc. Description Values of member variables can be defined and retrieved through public get and set methods using the sign. Description Member functions that allow the object to do things. Method that runs when an instance of class is created. Method that runs when an object is destroyed. Description Message sent from an event source object to another object(s), called the event receiver(s). Let s look at our Instrument class. To turn a tradable instrument into a class in Visual C, we need to think about the properties of an instrument, i. e. what are the nouns associated with it, such as the symbol and price, as well as the verbs, or functionalities, or behaviours, of an instrument, such as setting and returning the price or entering an order. When we come up with a list of nouns, the what it is of an object, and verbs, the what it does, we say that the object has been abstracted. Let s assume that we have fully abstracted our Instrument class into the nouns and verbs shown in Table 4-2. TABLE 4-2 Nouns Symbol Bid Ask Last Trade Price Last Trade Qty Bid Qty Ask Qty Expiration Verbs Enter Order Cancel Order(s) Description The ticker symbol (unique identifier) of the instrument. The highest bid price. The lowest ask price. The price at which the last trade was executed. The quantity of the last trade. The volume on the bid price in the exchange order book. The volume on the ask price in the exchange order book. The date of the expiration of the instrument, if any. Description Sends an order to the exchange. Sends a request to the exchange to cancel an order or orders. 36 4.5. MEMORY MANAGEMENT IN Encapsulation Encapsulation is the process of containing abstracted data and functionalities into a class, exposing to the outside world only those methods that absolutely must be exposed, which are then known collectively as the class public interface. So, classes hide the implementation of their properties and methods and communicate with the external programming environment through the public interface. In this way, encapsulation protects the object from being tampered with and frees the programmer from having to know the details of the object s implementation. In our Instrument class example, because the outside programming environment does not need to be exposed to the method of retrieving the real-time bid or ask price, this functionality is encapsulated and made invisible to the outside world Inheritance Within an automated trading system, we need to represent tradable instruments in code. A futures contract is a tradable instrument, as is a stock or an option. All of these could become objects in our program so we will need to create classes for these. However, all of these are also instances of the Instrument class as we have abstracted it. The Instrument class contains only those properties and methods that are common to all tradable instruments. In order to represent a futures contract in our program, we could create a new Futures class that inherits from the Instrument class. As such, the Futures class would inherit all the properties and methods from the base, or parent, Instrument class. The Futures class then may have some added properties or functionalities that are unique to futures contracts. Likewise, we could create an Option class that inherits from the Instrument class and has its own specific functionalities added on. A derived class can add functionality beyond that of the base class and it can also override methods of its base class, i. e. a derived class may replace a member function definition of the base class with its own new definition. It is important to note that Visual C provides for three types of classes references types, value types, and unmanged types and the abilities and intricasies of inheritance differ among the three types. As you will see, s common type system dictates that all reference types inherit from the base Object class Polymorphism Briefly, polymorphism allows us to have one method name, or function name, used in different derived classes, but yet have different implementations, or functionalities, associated with that name depending on the class. In a CallOption class and a PutOption class, for example, we may have inherited a BlackScholesPrice() method from the parent Option class, but yet each of the derived classes has their own method for calculation, as the equations for Black Scholes call and put pricing are different Memory Management in In, there are four memory spaces managed and unmanaged stacks and managed and unmanaged heaps. It Doesnt Seem Possible. Aber es ist mit unseren algorithmischen Handelsstrategien Es scheint nicht möglich zu sein. Ein algorithmisches Handelssystem mit so viel Trendidentifikation, Zyklusanalyse, Buysell-Seitenvolumenströmen, Mehrfachhandelsstrategien, dynamischer Einstieg, Ziel - und Stopppreise und ultraschnelle Signaltechnik. Aber es ist. In der Tat ist AlgoTrades algorithmische Handelssystem-Plattform die einzige seiner Art. Nicht mehr auf der Suche nach heißen Aktien, Sektoren, Rohstoffen, Indizes oder Lesemarkt-Meinungen. Algotrades macht alle Suche, Timing und Handel für Sie mit unserem algorithmischen Handelssystem. AlgoTrades bewährte Strategien können manuell durch das Empfangen von E-Mail - und SMS-Textwarnungen befolgt werden, oder es kann 100 Freisprechhandeln sein, sein bis zu Ihnen Sie können den automatisierten Handel jederzeit einschalten, so dass Sie immer die Kontrolle über Ihr Schicksal haben. Automatisierte Handelssysteme für Savvy Investoren Copyright 2017 - ALGOTRADES - Automatisiertes algorithmisches Handelssystem CFTC RULE 4.41 - HYPOTHETISCHE ODER SIMULATIERTE LEISTUNGSERGEBNISSE HABEN BESTIMMTE EINSCHRÄNKUNGEN. UNTERNEHMEN EINE TATSÄCHLICHE LEISTUNGSAUFNAHME, ERFOLGREICHE ERGEBNISSE NICHT VERTRETEN AKTUELLES HANDEL. AUCH AUCH DIE HÄNDLER HABEN NICHT AUSGEFÜHRT WERDEN, DIE ERGEBNISSE KÖNNEN UNTER - ODER ODER ÜBERGANGSERKLÄRUNG FÜR DEN AUSWIRKUNGEN, WENN JEDOCH, BESTIMMTE MARKTFAKTOREN, WIE LICHT DER LIQUIDITÄT. SIMULIERTE HANDELSPROGRAMME IN ALLGEMEINEN SIND AUCH AUF DIE TATSACHE, DIE SIE MIT DEM BENEFIT VON HINDSIGHT ENTWICKELT WERDEN. KEINE REPRÄSENTATION IST GEMACHT, DASS JEDES KONTO WIRD ODER IST, WIE GEWINNEN ODER VERLUSTE ÄNDERN ZU DIESEM ANGEBOT ZU ERHÖHEN. Es wird keine Vertretung gemacht, noch bedeutet, dass die Verwendung des algorithmischen Handelssystems Einkommen generieren oder einen Gewinn garantieren wird. Es besteht ein erhebliches Verlustrisiko im Zusammenhang mit Futures-Handels - und Handelsbörsen. Futures-Handels - und Handelsbörsen handelnde Fonds beinhalten ein erhebliches Verlustrisiko und sind für alle nicht geeignet. Diese Ergebnisse basieren auf simulierten oder hypothetischen Leistungsergebnissen, die gewisse inhärente Einschränkungen aufweisen. Anders als die Ergebnisse, die in einem tatsächlichen Leistungsrekord gezeigt werden, stellen diese Ergebnisse nicht den tatsächlichen Handel dar. Auch weil diese Geschäfte nicht tatsächlich ausgeführt wurden, können diese Ergebnisse die Auswirkungen von bestimmten Marktfaktoren, wie zB Liquiditätsverlust, unter - oder überkompensiert haben. Simulierte oder hypothetische Handelsprogramme im Allgemeinen unterliegen auch der Tatsache, dass sie mit dem Vorteil der Nachsicht entworfen sind. Es wird keine Vertretung gemacht, dass ein Konto eine Gewinne oder Verluste erzielen wird, die diesen ähnlich sind. Informationen auf dieser Website wurden ohne Rücksicht auf bestimmte Investoren Investitionsziele, finanzielle Situation und Bedürfnisse vorbereitet und weiter beraten Abonnenten nicht auf Informationen zu handeln, ohne spezifische Beratung von ihren Finanzberater nicht auf Informationen von der Website als primäre Basis zu verlassen Für ihre Anlageentscheidungen und ihr eigenes Risikoprofil, Risikotoleranz und eigene Stopverluste zu berücksichtigen. - powered by Enfold WordPress ThemeBuilding Automated Trading Systems. With an Introduction to Visual C 2005 Transcription 2 Building Automated Trading Systems With an Introduction to Visual C 2005 3 The Financial Market Technology Series Series Editor Ben Van Vliet The Financial Market Technology Series is a partnership between Elsevier, Inc. and the Institute for Market Technology (i4mt) to publish cutting-edge books covering topics concerning the integration of technology with financial markets, including: automated trading, building trading and investment systems, operational issues in back office processing, clearing and settlement, and compliance and governance issues as they relate to technology. The goal of the series is to promote increased understanding and competency with technology in the finance industry through publishing high-quality books on the latest areas of research and practice for professionals working in the financial markets. Series Editor: Ben Van Vliet is a Lecturer in and the Associate Director of the M. Sc. in Financial Markets Program at the Stuart Graduate School of Business, Illinois Institute of Technology. Within this program, he teaches graduate courses in quantitative finance and automated trading system development using Visual Basic, SQL, XML, ISO C and Visual C and UML. He is also a co-inventor of TraderDNA, a real-time trading performance evaluation software package, as well as being a Director at TraderDNA LLC. He also serves as Vice Chairman of the Institute for Market Technology (i4mt), a notfor-profit organization that provides educational programs in financial markets and technology, where he also chairs the Market Technology Committee for the Certified Trading System Developer (CTSD) program. Please see for further information. Mr. Van Vliet also consults extensively in the financial industry. He is the author of Building Automated Trading Systems (Academic Press, 2007) and co-author of Modeling Financial Markets (McGraw-Hill 2004). We welcome proposals for books for the series. Please go to where you will find a link to send us your proposal. 4 Building Automated Trading Systems With an Introduction to Visual C 2005 Benjamin Van Vliet AMSTERDAM BOSTON HEIDELBERG LONDON NEW YORK OXFORD PARIS SAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYO Academic press is an imprint of Elsevier 5 Academic Press is an imprint of Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, USA 525 B Street, Suite 1900, San Diego, California. USA 84 Theobald s Road, London WC1X 8RR, UK This book is printed on acid-free paper. Copyright 2007, Elsevier Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopy, recording, or any information storage and retrieval system, without permission in writing from the publisher. Permissions may be sought directly from Elsevier s Science amp Technology Rights Department in Oxford, UK: phone: (44). fax: (44). You may also complete your request on-line via the Elsevier homepage (elsevier), by selecting Support amp Contact then Copyright and Permission and then Obtaining Permissions. Library of Congress Cataloging-in-Publication Data Van Vliet, Benjamin Building automated trading systems. with an introduction to Visual C 2005 Benjamin Van Vliet. p. cm. Includes bibliographical references and index. ISBN (alk. paper) 1. Electronic trading of securities. 2. Finance Mathematical models. 3. Microsoft Visual C Microsoft. I. Title. HG V dc British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library. ISBN 13: ISBN 10: For information on all Academic Press publications visit our Web site at Printed in the United States of America 6 Contents Acknowledgments xiii CHAPTER 1 Introduction ISO C Structure of This Book 2 Section I: Introduction to Visual C 2005 CHAPTER 2 The Framework MS Visual Studio 2005 Project Structure What is CCLI Why Visual C The VC Compiler What About Speed The Framework Sample Code: MessageBoxExample Sample Code: StringConcatExample Sample Code: DebugExample Versioning Summary 14 CHAPTER 3 Tracking References Sample Code: TrackingReferenceExample Sample Code: TemplateFunctionExample Managed Handle Sample Code: Ref TypeExample Summary 17 v 7 vi Contents CHAPTER 4 Classes and Objects Abstraction Encapsulation Inheritance Polymorphism Memory Management in NET Types Unmanaged Types Mixed Assemblies Summary 23 CHAPTER 5 Reference Types Sample Code: Ref TypeExample Delete and Dispose Finalize Sample Code: FinalizeExample Stack Semantics for Ref Types Nullptr Reference This is Important Summary 31 CHAPTER 6 Value Types Sample Code: ValueTypesExample Sample Code: PassingValueTypesExample Summary 36 CHAPTER 7 Unmanaged Objects Sample Code: UnmanagedObjectExample Summary 39 CHAPTER 8 Composition Sample Code: CompositionExample Sample Code: UnmanagedCompositionExample Sample Code: ManagedCompositionExample Summary 48 CHAPTER 9 Properties Sample Code: PropertiesExample Summary 50 CHAPTER 10 Structures and Enumerations Sample Code: ValueStructureExample Sample Code: ReferenceStructureExample Sample Code: EnumsExample Summary 53 8 Contents vii CHAPTER 11 Inheritance Access Modifi ers Object Class Abstract and Sealed Classes Sample Code: InheritanceExample Interfaces Sample Code: InterfaceExample Runtime Callable Wrapper Summary 60 CHAPTER 12 Converting and Casting Converting Sample Code: ConvertExample Static Casting Sample Code: StaticCastExample Dynamic Casting Sample Code: DynamicCastExample Safe Casting Sample Code: SafeCastExample Summary 65 CHAPTER 13 Operator Overloading Sample Code: OpOverloadExample Summary 69 CHAPTER 14 Delegates and Events Delegates Sample Code: DelegatesExample Multicasting Sample Code: MulticastExample Events Sample Code: EventExample Wrappers Sample Code: WrapperExample Asynchronous Method Calls Sample Code: AsynchEventExample Summary 82 CHAPTER 15 Arrays Sample Code: ManagedArrayExample Sample Code: PassingArraysExample Summary 85 vii 9 viii Contents CHAPTER 16 Generating Random Numbers Sample Code: RandomExample Sample Code: StdNormRandomExample Summary 89 CHAPTER 17 Time and Timers Sample Code: MillisecondsExample Stopwatch Sample Code: StopwatchExample Timers Sample Code: FormsTimerExample Sample Code: ThreadingTimerExample Sample Code: TimersTimerExample Summary 98 CHAPTER 18 Input and Output Streams FileStream Class StreamWriter Class File and Directory Classes Application Class FileMode Enumeration Sample Code: StreamWriterExample Sample Code: StreamReaderExample Summary 101 CHAPTER 19 Exception Handling Sample Code: ExceptionsExample Catching Unmanaged C Types Summary 105 CHAPTER 20 Collections Sample Code: HashtableExample Sorted List Class Sample Code: SortedListExample Thread Safety Generics Sample Code: LinkedListExample Sample Code: GenericsExample Summary 112 CHAPTER 21 STLSTL Sample Code: STLExample Sample Code: STLExample Summary 114 10 Contents ix CHAPTER 22 DataSets Sample Code: DataSetExample Rows, DataRowCollections, and DataRows Summary 117 CHAPTER 23 Connecting to Databases Database Connection DataAdapter Sample Code: ADOExample Enumerating Through All the Data in a DataSet Using Excel as a Data Source Writing XML from a DataSet Updating a Database with Changes in a Dataset Retrieving Data with a DataReader Summary 124 CHAPTER 24 Structured Query Language Data Manipulation Language Updating a Database with Changes in a DataSet Data Defi nition Language Summary 140 CHAPTER 25 XML Well-Formed XML Documents Valid XML Documents XML Schema Documents Parsers Sample Code: Traders. xsd Sample Code: XmlWriterExample Sample Code: XmlReaderExample Summary 146 CHAPTER 26 Financial Information Exchange Protocol XML Protocols in Financial Markets Overview of FIX Summary 151 CHAPTER 27 Serialization SerializationExample Summary 154 CHAPTER 28 Windows Services Sample Code: WindowsServiceExample Summary 159 11 x Contents CHAPTER 29 Setup and Installation Packages Sample Code: InstallationExample Summary 162 Section II: Concurrency CHAPTER 30 Threading Threading Namespace Sample Code: ThreadExample Sample Code: ThreadAbortExample Thread Priority Sample Code: ThreadPriorityExample ThreadState Enumeration ThreadPool Class Sample Code: ThreadPoolExample Updating Forms from Other Threads Sample Code: FormUpdateExample Thread Safety Summary 175 CHAPTER 31 Synchronization Classes Sample Code: SynchronizeExample Mutex Class Example Code: MutexExample Semaphore Class Sample Code: SemaphoreExample Monitor Class Sample Code: Monitor Summary 182 CHAPTER 32 Sockets Sample Code: SynchronousServerExample Sample Code: SynchronousClientExample Summary 189 Section III: Interoperability and Connectivity CHAPTER 33 Marshaling Marshal Class Sample Code: StringToCharArrayExample Summary 194 CHAPTER 34 Interior and Pinning Pointers Sample Code: InteriorPointerExample Pinning Pointers Sample Code: PinningExample Summary 198 12 Contents xi CHAPTER 35 Connecting to Managed DLLs Example Code: DLLExample Summary 201 CHAPTER 36 Connecting to Component Object Model (COM) DLLs with COM Interop Sample Code: MyCOMLibrary Sample Code: UsingCOMDLLExample Summary 207 CHAPTER 37 Connecting to C DLLs with Platform Invocation Services Calling C-Style Functions Sample Code: MyWin32Library Sample Code: UsingWin32DLLExample Creating Objects Sample Code: MyWin32ClassLibrary Sample Code: UsingWin32ClassExample CallingConventionEnumeration Summary 216 CHAPTER 38 Connecting to Excel Sample Code: ControllingExcelExample Sample Code: ExcelChartExample Summary 221 CHAPTER 39 Connecting to TraderAPI TraderAPI Overview FillObj InstrObjClass InstrNotifyClass OrderObj OrderProfi leclass OrderSetClass Sample Code: TraderAPIConnectionExample Summary 230 CHAPTER 40 Connecting to XTAPI Sample Code: XTAPIConnectionExample Summary 233 13 xii Contents Section IV: Automated Trading Systems CHAPTER 41 Building Trading Systems Buy vs. Build Data Mapping Speed of Development Ten Things that Affect the Speed of a Trading System Getting It Right Logic Leaks Ten Things that Affect the Profi tability of a Trading System Summary 245 CHAPTER 42 K V Trading System Development Methodology The Money Document Research and Document Calculations Back Test Implement Manage Portfolio and Risk Summary 257 CHAPTER 43 Automated Trading System Classes Instrument Class Order Class Order Book Bracket Tick Tick or Bar Collection Bar System Manager Graphical User Interface Summary 265 CHAPTER 44 Single-Threaded, Technical Analysis System Sample Code: TechincalSystemExample Summary 277 CHAPTER 45 ProducerConsumer Design Pattern Sample Code: ProducerConsumerExample Summary 287 CHAPTER 46 Multithreaded, Statistical Arbitrage System Sample Code: SpreaderExample Summary Conclusion 304 14 Acknowledgments This book began as the class notes for a course I teach at the Illinois Institute of Technology called Advanced Object Oriented Programming for Financial Markets. In this class we cover automated trading system design and development using Microsoft Visual C. When I started teaching this course several years ago, I could not find a book that covered all the topics necessary to build real-time, automated trading systems and so, as a result, this book attempts to do just that it brings together programming and technology-related topics for the development of trade selection, order routing, order management, and position management algorithms. I do hope that more schools will offer courses on automated trading system design in the future and that this book will be helpful in their instruction. Furthermore, this book is a foundation text for the CTSD Certified Trading System Developer program offered by the Institute for Market Technology (i4mt. org). This is a new certification program that consists of three examinations, one in quantitative finance, one in securities and derivatives trading strategy, and one in ISO CC programming and market technology. This rigorous self-study program is designed to bring together the skillsets in demand in the financial industry today. Candidates who achieve the CTSD designation will be talented people indeed. As one can imagine, additional credit for the completion of this project must be given to many friends, family, and colleagues: in particular to my wife, Julia, Mark McCracken, Dr. Andrew Kumiega, Andrew Acosta, Sagy Mintz, Jason Malkin, Larissa J. Miller, Derek Walther, Niraj Chokshi, Julian Mulla, Mike Hermanson, David Norman, Dr. Deborah Cernauskas, Dr. Joe Wojkowski, Pamela Reardon, Edward Wang, Alex Deitz, Andrew Robinson, and all my colleagues at the IIT Center for Financial Markets Russell Wojcik, Dr. Michael Gorham, Keith Black, Dr. Michael Ong, Dr. John Bilson, Dr. Michael Kelly, and Jodi Houlihan. Also I would like to thank the many students who have taken my course and have all provided valuable feedback. Without their help and the help of many others this book would never have been completed. xiii 15 xiv Acknowledgments This book is written for people with knowledge of ISO C or possibly Java,, or COM. For financial engineers and aspiring financial engineers with a general programming background, this book will provide an in-depth discussion of higher level programming concepts such as event handling, interoperability, data feed connectivity, and concurrency. For experienced C programmers, you may find that this book provides a good introduction to the use of C within the Framework. Whatever the case, I hope you learn from it and are inspired to delve deeper into the topic of automated trading system development. Please provide me with any feedback you have. I pledge to update my website, regularly with corrections to errata and additional examples. 16 CHAPTER 1 Introduction Automated (or algorithmic) trading systems consist of many parts, both hardware and software clients, servers, networks, databases, calculation engines, application programming interfaces, real-time data feeds, and graphical user interfaces. However, the business logic of trading systems, which consists of trade selection algorithms, order management, and position management logic, is contained within software, and this book is concerned with the encapsulation of trading system business logic in software that controls the flow of market data. (There is no quant in this book.) An automated trading system consists of the rules for entry into and exit from a position or positions and the technology, both hardware and software, used to make them happen. These rules are a set of logical or mathematical operations that can be based on qualitative, technical, or quantitative research. If we want to build an automated system that executes trades on electronic exchanges, we need to learn how to work with data, both real-time market data and historical data, in code. After all, data is the lifeblood of electronic markets, according to David Norman in his book Professional Electronic Trading. That s just what this book is about, using Visual C to manage financial markets data (and there is a lot of it) in trading system applications. Generally speaking, this book covers three things: 1. Managing data in memory. 2. Storing data in and retrieving from databases. 3. Communicating data. Front office programming in financial markets is largely concerned with connecting to databases, real-time data feeds, order execution platforms, quant libraries, optimization engines, charting software, report generation engines, legacy technologies, and Excel, just to name a few. In order to successfully manage real-time and historical data, we will need to understand: 1. Event-driven architecture. 2. Concurrency. 3. Connectivity and interoperability. 1 17 2 CHAPTER 1 Introduction While this book addresses dozens of important technological issues that you will face when building real-world automated trading systems in, it does not show you how to build a profitable trading system. (It is important nevertheless to recognize that technological superiority can be a major competitive advantage.) There are four disciplines that go into automated trading system development computer science, quantitative finance, trading strategy, and quality management and this is a computer science book. Development and testing of trade selection and risk management methods are topics for other books. This book covers the basics of what a financial engineer should know about programming in objects, SQL, multithreading, interoperability, messaging, order selection algorithms, and order management techniques. In this text, I have tried to include market-driven, job-relevant information. Today s employers in the financial markets demand job readiness. If you want to get a job in the trading and money management industry, which more and more every day is driven by automated systems, you will have to have a competitive level of knowledge of programming. You should realize that this book is an overview, however. It will not teach you everything. Technology as a topic is obviously far too vast to cover in one book. Even narrowing it down to VC for trading system development is still far too vast. Over the pages, I will present several important ideas, try to point you in the right direction, and hopefully in the end inspire you to do additional research on the topic of automated trading system development. From there, the diligent financial engineer must investigate further on his or her own ISO C This book covers the programming aspects of trading system development and assumes that you are familiar with ISO C programming concepts, including pointers, functions, objects, and the Standard Template Library Structure of This Book Automated trading systems find their purest form in high-frequency strategies where speed of calculation and execution are the competitive advantage. Other systems, where milliseconds are not necessarily of the essence, may be fully automated or partially automated. This text will focus on introducing programming and design concepts for higher frequency systems. Discussion of all the alternative technological concepts of trading system design and presentation of a complete trading system are beyond the scope of a book. The trading systems presented in this book are drastically simplified in order to illustrate common programming and design concepts. This book is divided into four sections. The first section focuses purely on an introduction to Visual C types and programming techniques. The second section focuses on multithreading. The third focuses on interoperability and connectivity and the fourth on objects, design patterns, and architectural concepts for automated trading system development. In the end, simply reading this book will not make you an expert. To really learn the material in this book, you should also work through the code samples presented. Only by involving yourself in the process, and furthermore going beyond it, will you gain understanding and intuition. It s hard work, but it will pay off. 18 SECTION I Introduction to Visual C 2005 19 This page intentionally left blank 20 CHAPTER 2 The Framework 2.1. MS Visual Studio 2005 Project Structure In MS Visual Studio 2005, your software application is called a solution, and a solution can be made up of one or more projects, where each project could potentially be in a different Visual Studio language. Over the course of this book, I will present solutions developed for the most part in MS Visual C for managed or applications for reasons that I will explain shortly. However, be aware that Visual C is not a new programming language, but rather a full development environment that provides increased support for many C project types, including: Active Template Library (ATL) projects. MS Foundation Classes (MFC) projects. or managed console, Windows or DLL projects. Win32 Console projects for ISO C projects. Win32 API projects and DLLs. As a result, Visual C for or managed projects is just one of several C languages offered within Visual Studio 2005, and this is one of the things that sets the new VC apart from the others in the family it provides essentially five independent C languages in one package. So if you want to continue making MFC applications, you can do that just like before. In fact, support for MFC and ATL has actually been improved in VS In previous versions of Visual Studio, the extension was added to the name in order to differentiate it from even earlier versions, such as Visual Basic 6.0. With the advent of VS 2005, the extension to the name is usually left off and we can refer to them as VB, C, and Visual C What is CCLI CCLI (Common Language Infrastructure) is a derivation of C. According to Stanley Lippman of Microsoft: 5 21 6 CHAPTER 2 The Framework CLI refers to the Common Language Infrastructure, a multitiered architecture supporting a dynamic component programming model. In many ways, this represents a complete reversal of the C object model. A runtime software layer, the virtual execution system, runs between the program and the underlying operating system. Access to the underlying machine is fairly constrained. Access to the types active in the executing program and the associated program infrastructure both as discovery and construction is supported. The slash () represents a binding between C and the CLI So, a first approximation of an answer to what is CCLI is that it is a binding of the static C object model to the dynamic component object model of the CLI. In short, it is how you do programming using C rather than C or Visual Basic. Like C and the CLI itself, CCLI is undergoing standardization under the European Computer Manufacturers Association (ECMA) and eventually under ISO. The common language runtime (CLR) is the Microsoft version of the CLI that is specific to the Windows operating system. Similarly, Visual C is the implementation of CCLI. As a second approximation of an answer, CCLI integrates the programming model within C in the same way as, back at Bell Laboratories, we integrated generic programming using templates within the then existing C. In both of these cases your investments in an existing C codebase and in your existing C expertise are preserved. This was an essential baseline requirement of the design of CCLI. Over the course of this book, I will simply refer to Microsoft implementation of CCLI as Visual C. For Mr. Lippman s full article, go to msdnmagissues0600purecdefault. aspx Why Visual C So why Visual C What are the benefits of managed or C applications Simply put and in the words of a vice president of a major trading software vendor here in Chicago, NET is the future. Most importantly, the Framework contains many, many classes that aid in development of trading systems, as we will see. Furthermore, relative to the other languages, VC contains much greater support for interoperability between managed and unmanaged code. In addition, in financial markets, interoperability is key. In VC, we have precise control over managed and unmanaged heap and stack memory allocation and managed and unmanaged code and all can exist seamlessly in the same project. This permits us to integrate our existing C applications, functionality, and objects quickly and easily into new applications. This is especially true for COM applications, which are used heavily in the financial industry and are unmanaged. Further, if you have libraries of objects or financial functions written in native C, VC with its extensive managedunmanaged interop support will give you tremendous control. Alternatively, if you have existing C applications that you wish to convert to, again VC will provide you with the tools the other languages can t and don t. Finally, while the 2005 version of the STL (known as STL) is not available quite yet, it will be soon and converting native STL-dependent code will be a breeze. 22 2.6. THE FRAMEWORK The VC Compiler Here are a few things to remember about the VC compiler. The VC compiler, C1.exe, uses the. c extension for C-only compiling and. cpp for C and C. Also, the standard headers do not require the. h extension, as Microsoft has included its own versions of these files in the std namespace. Further, a project s properties window displays all of the compiler settings for CC, including the linker and build events. Microsoft s Cl. exe compiler implements ANSI C and ISO C standards and is 98 C compliant according to Microsoft. The compiler offers Solution Configurations for Debug builds and Release builds. With a Debug build, we can interact with our code during runtime. This is a big help. However, no optimizations are made and for that we use the Release build, which will generate faster, optimized code. The compiler allows us to incorporate native C code in our projects and first compiles into Microsoft Intermediate Language (MSIL). Then the MSIL is converted into native code by the Just In Time (JIT) compiler. With JIT some operations will be faster than native C, whereas others will be slower. As a result, there are trade-offs between development speed and execution speed. However, there are things we can do to minimize the cost of certain operations. The VC compiler and JIT can be tuned to generate the fastest possible code using the available compiler options. If you are serious about speed, take some time to investigate further Microsoft s VC compiler What About Speed Speed is important, of course. For an in-depth discussion of speed considerations in managed code, I will refer you to a few excellent articles in the MSDN Library (msdn. microsoft. comlibrary): A Baker s Dozen: Thirteen Things You Should Know Before Porting Your Visual C Programs to Visual Studio 2005 by Stanley Lippman. Best Practices for Writing Efficient and Reliable Code with CCLI by Kenny Kerr. C: The Most Powerful Language for Framework Programming by Kenny Kerr. Writing Faster Managed Code: Know What Things Cost by Jan Gray. Writing High-Performance Managed Applications: A Primer by Gregor Noriskin (includes an overview of the CLR Profiler). Tips for Improving Time-Critical Code. Optimization Best Practices in the Visual C section The Framework When we create managed Visual C applications, our programs are developed, compiled, and executed within the Framework. The Framework consists of three parts: 23 8 CHAPTER 2 The Framework 1. Common Language Runtime (CLR). 2. Class Libraries. 3. ASP. ASP is Microsoft s web development platform for building enterprise web applications, which run too slow for real-time, financial markets application, and so we will spend no time examining it. Rather we will spend our time learning about the common language runtime and the class libraries and how we can use them to build financial applications that can potentially run on multiple operating systems, not just Windows, including Unix, Linux, and Mac Common Language Runtime The CLR drives code execution within the Framework and provides-based programs with cross language integration, security, dynamic memory management, and debugging services. Further, the CLR controls what we call managed code, which is executed within the managed heap. That is to say, the managed heap is controlled by the Framework rather than the operating system. Unmanaged code (or non - code), however, is controlled by the operating system. The CLR also provides for dynamic memory management by using a garbage collector to manage the allocation and deallocation of memory space, eliminating the common memory leak problems that often occur in software. The CLR s allocation of memory on the managed heap is, it turns out, actually faster than unmanaged heap allocation and nearly as fast as stack memory allocation because it allocates contiguous memory locations by simply incrementing a pointer. In, the compiler compiles managed source code first into MSIL. Before code is run, MSIL is converted by a just-in-time (JIT) compiler specific to your computer architecture. JIT converts MSIL into machine language, or native code, at runtime Garbage Collection The garbage collector determines the best time to perform a collection of unreferenced objects. The garbage collector releases the memory space allocated to objects that are no longer being referenced (or, pointed to) within the application. The Framework keeps a list of active references that the JIT compiler and the CLR maintain. The garbage collector uses this list to examine all of an application s references. Objects that are not on the list are considered unreachable and the memory space will be released. As a result, the garbage collector examines the managed heap and finds blocks of space occupied by unreferenced objects. At the same time, referenced memory locations are compacted and moved and the necessary updates to the pointer references are made. It s important to note then that the garbage collector will be moving objects around in memory without our knowledge. This has important implications later on Assemblies Assemblies form the fundamental building blocks for the Framework and any application developed within it. Assemblies most often exist as executable files or dynamic link library files and contain groups of classes that form a logical functional unit. 24 2.7. SAMPLE CODE: MESSAGEBOXEXAMPLE 9 Assemblies contain information about content, versioning, and dependencies as a result the applications we create with Visual C do not need to rely on registry values to work properly. Since registry is not required, we can generally install Visual C applications by simply copying the executable s directory onto the target computer Namespaces Namespaces organize the thousands of classes in the libraries, prevent ambiguity, and simplify references, as we will see. (VC programs that we write will often contain or use multiple namespaces.) In the System namespace is the root namespace and contains primitive data types and fundamental classes such as Object (from which all objects are derived), String, Exception, and the garbage collector class, GC. The Visual Studio Documentation (the Help Files) contains a Framework Class Library Reference page that provides a comprehensive list of the namespaces with descriptions. Since all programming in depends on the objects contained in these namespaces, you may want to spend some time familiarizing yourself with the different namespaces and the types of objects they contain Fully Qualified Names When using libraries, we can instantiate objects defined in external locations, as long as we add a reference to the assembly and then use the fully qualified name for the class in our code. A fully qualified name is a class reference that is prefixed with its namespace name. Here is an example of how to create an object using the fully qualified class name for a class in another namespace: System::Windows::Forms::MessageBox::Show( Hello, world ) Fully qualified names prevent naming conflicts because the compiler can always determine which class is being used. However, the names themselves can get long and cumbersome. As a way around this, we can use the using namespace statement. The following code uses this shortcut: using namespace System::Windows::Forms MessageBox::Show( Hello, world ) As you will see, within our own user-defined namespaces, we can define modules, interfaces, classes, delegates, enumerations, structures, and even other namespaces Sample Code: MessageBoxExample Let s create a new Visual C program that will illustrate the use of namespaces. Step 1. Start Visual Studio Step 2. In the File menu item, click on New and Project The New Project window will appear (Figure 2-1). Step 3. Highlight Visual C Projects in the Projects Types pane and CLR Console Application in the templates pane. Also, be sure to give your project a name and a location. OK klicken. 25 10 CHAPTER 2 The Framework When your solution is ready, you should see the Solution Explorer window on the righthand side of your screen. If not, click on the icon as shown. The Solution Explorer will allow you to navigate through the files that comprise your solution (Figure 2-2). Because our Console Application does not by default allow for a user interface, we need to add a reference to the System::Windows::Forms namespace. The Forms namespace contains the class definitions for Windows forms. FIGURE 2-1 FIGURE 2-2 26 2.8. SAMPLE CODE: STRINGCONCATEXAMPLE 11 Step 4. In the Solution Explorer window, right click on the project name and select References The MessageBoxExample Property Pages window will appear. Click on the Add New Reference icon. In the list of components, navigate down to System::Windows::Forms. Click Select and then click OK. The References directory in the Property Pages window should now list System. Windows::Forms. Step 5. In the MessageBoxExample. cpp code window, type the following: MessageBoxExample. cpp. main project file. include stdafx. h using namespace System using namespace System::Windows::Forms int main(arrayltsystem::stringgtargs) Console::WriteLine(L Hello, World ) MessageBox::Show( Hello, World ) return 0 Step 6. Compile the program by clicking the Build menu item and Build MessageBox Example. Run the program by clicking the Debug menu item and Start Without Debugging. Notice again that the MessageBox class definition is located within the System. Windows::Forms namespace. (Using the optional L before a string constant designates the native, wide character type wchart.) 2.8. Sample Code: StringConcatExample Concatenating strings for display can be done in many ways as can formatting numbers for display using the String class or the ToString method as shown. The StringBuilder class also comes in handy. In order to use the StringBuilder class, use the System::Text namespace as shown. include stdafx. h using namespace System using namespace System::Text int main(arrayltsystem::stringgt args) String mlang C int my 2005 27 12 CHAPTER 2 The Framework Console::WriteLine( This is Visual 0 1, mlang, my) Console::WriteLine(String::Concat( This is Visual, mlang. my)) Console::WriteLine( This is Visual mlang my) Notice the formatting possible using the ToString method. Console::WriteLine(Math::PI. ToString( . )) StringBuilder mbuilder gcnew StringBuilder( This is Visual C ) mbuilder-gtappend(my) Console::WriteLine(mBuilder) return 0 2.9. Sample Code: DebugExample Here is another example that illustrates the use of the Debug class and the Output Window. Step 1. Start Visual Studio 2005 as before. This time highlight Visual C Projects in the Projects Types pane and Windows Forms Application in the templates pane. Again, be sure to give your project a name and a location. Step 2. The Form1.h Design Window should appear. Double click on your Form1 and Visual Studio will automatically generate an event handler for the Form1 load event. This function will run when Form1 loads. Add the following code to the method: private: System::Void Form1Load(System::Object sender, System::EventArgs e) Debug::WriteLine( Hello, World ) The output of this program does not show a message box, but rather will print the output through the Debug class, which is defined in the System::Diagnostics namespace, which we will need to add. Step 3. In the Form1.h code window, be sure to add: using namespace System::Diagnostics Here is what the completed, Form1 code window should look like. pragma once namespace DebugExample using namespace System using namespace System::ComponentModel using namespace System::Collections 28 2.9. SAMPLE CODE: DEBUGEXAMPLE 13 using namespace System::Windows::Forms using namespace System::Data using namespace System::Drawing using namespace System::Diagnostics public ref class Form1. public System::Windows::Forms::Form public: Form1(void) InitializeComponent() protected: Form1() if (components) delete components private: System::ComponentModel::Container components Windows Forms Designer generate code private: System::Void Form1Load(System::Object sender, System::EventArgs e) Debug::WriteLine( Hello, World ) Step 4. Build your application and then run it using the blue Start icon on your task bar. To view the output, view the aptly named Output window (Figure 2-3). If you cannot find it, click on the Other Windows icon. We often use the static methods of the Debug class to print program information and to check program logic. Use of the Debug class does not impact the performance of the application. 29 14 CHAPTER 2 The Framework FIGURE Versioning The Framework provides help with project versioning. In a project s AssemblyInfo. cpp file, we can set the version number easily. Version information for an assembly consists of the following four values: Major Version Minor Version Build Number Revision You can specify all the value or you can default the Revision and Build Numbers by using the as shown next: assembly:assemblyversionattribute( 1.0. ) Summary This chapter reviewed the VC solution structure, how assemblies and namespaces are organized, how the CLR controls managed memory, and the garbage collector. Also, we developed some simple solutions to illustrate use of message boxes, the debug window, the console window, and string concatenation. Finally, we looked at some of the reasons why VC is such a great language for developing automated trading systems. 30 CHAPTER 3 Tracking References Because a referenced type may be moved around at runtime by the common language runtime (CLR), the native C amp cannot be used to reference an object on the garbage collected heap. In VC the CLR will update the new tracking reference with the new location. A tracking reference can refer to a managed or native object, a data member, or a storage location, but cannot be a member of a class. Also, by using a tracking reference in a template function, we can ensure that the function can be called with native, value, or reference types Sample Code: TrackingReferenceExample This example shows that the tracking reference replaces the native C amp reference. As you will see, however, we will still use the native amp on occasion. include stdafx. h using namespace System int main(arrayltsystem::string gt args) int x 3 int ampa x int b x Console::WriteLine(x) Console::WriteLine(a) Console::WriteLine(b) return 0 15 31 16 CHAPTER 3 Tracking References 3.2. Sample Code: TemplateFunctionExample For now, do not worry about the distinction between a ref class, a native class, and a value class. This is not a fully working code example as the class definitions are left out. Here, simply note the use of the tracking reference operator in the template function. include stdafx. h include MyRefClass. h include MyNativeClass. h include MyValueClass. h using namespace System templatelttypename Tgt void function1(t) int main(arrayltsystem::string gt args) MyRefClass mrefobj(3) MyNativeClass mnativeobj(4) MyValueClass mvalueobj(5) Managed Heap Stack Stack function1(mrefobj) function1(mnativeobj) function1(mvalueobj) return 0 templatelt typename T gt void function1(t manyobj) Console::WriteLine(mAnyObj. getValue()) VC supports templates and also things called generics, which we will look at in a later chapter Managed Handle Because a referenced object may be moved around at runtime by the common language runtime, the native C cannot be used to point on an object on the garbage collected, or managed, heap. In VC, replaces to declare a handle to an object on the managed heap and then uses gcnew rather than the traditional new keyword to create instances. Object member selection through this handle uses the arrow notation. 32 3.5. SUMMARY Sample Code: RefTypeExample This example will be explained in more detail in a later chapter. For now, just take note of the new notation, which declares a handle to a managed object. A handle, for our purposes, operates in a fashion logically equivalent to a C pointer. include stdafx. h include MyClass. h using namespace System int main(arrayltsystem::string gt args) MyClass mobj gcnew MyClass(2) Console::WriteLine(mObj-gtgetValue()) return 0 3.5. Summary This chapter looked at the new syntax for managed references, , and managed pointers, . We will be using managed references thoughout the book, so be sure you are comfortable with them before you proceed. 33 This page intentionally left blank 34 CHAPTER 4 Classes and Objects This book uses objects and object-oriented programming (OOP) to control program flow. OOP enables us to organize large programs logically and allows us to perform very large and complex tasks with fewer lines of code. Before we begin, let s review classes and objects. An object is an instance of a class and, in addition to our own classes, Microsoft s Framework gives us hundreds of ready-made classes in the namespaces. We can create instances of these classes as reference types and as such they will be managed by the common language runtime (CLR). Visual C is an object-oriented programming language. As such we will make use of classes, which have data and functionality together in their respective definitions. Classes have member variables or data members that store data and functionalities, or behaviors, held in procedures known as methods or member functions. As we will see, classes may also have events associated with them. The button click is an example of an event. In a working program, different objects work together, or talk to each other, through their respective public interfaces the collection of public methods exposed by an individual object. That is to say, private data within an object, which is not accessible from the outside world, is available to the outside programming environment only via the object s public interface. A major benefit of OOP is that because the data and methods encapsulated in classes are so closely tied together, we do not need to pass member variables back and forth as inputs to the member functions. Rather, member functions can access member variables directly within their definitions. If you are not overly familiar with classes, Table 4-1 shows elements that make up a class. In Visual C, we can create our own user-defined classes and create objects based on them. For example, we could create a class called Instrument. In a program, a real-life, tradable instrument would be an object, i. e. an instance of the Instrument class. Let s briefly review the four main concepts of object-oriented programming: abstraction, encapsulation, inheritance, and polymorphism Abstraction Abstraction is the process of creating an abstract model of a real-world object or thing. The process consists of taking the attributes, or properties, and functionalities, or methods, of a thing and turning them into logical pieces of data and functionality. 19 35 20 CHAPTER 4 Classes and Objects TABLE 4-1 Member Variables Variables Objects Properties Property Member Functions Methods Constructor Finalization Events Event Description Simple, primitive data. Other types classes, structures, interfaces, enums, etc. Description Values of member variables can be defined and retrieved through public get and set methods using the sign. Description Member functions that allow the object to do things. Method that runs when an instance of class is created. Method that runs when an object is destroyed. Description Message sent from an event source object to another object(s), called the event receiver(s). Let s look at our Instrument class. To turn a tradable instrument into a class in Visual C, we need to think about the properties of an instrument, i. e. what are the nouns associated with it, such as the symbol and price, as well as the verbs, or functionalities, or behaviours, of an instrument, such as setting and returning the price or entering an order. When we come up with a list of nouns, the what it is of an object, and verbs, the what it does, we say that the object has been abstracted. Let s assume that we have fully abstracted our Instrument class into the nouns and verbs shown in Table 4-2. TABLE 4-2 Nouns Symbol Bid Ask Last Trade Price Last Trade Qty Bid Qty Ask Qty Expiration Verbs Enter Order Cancel Order(s) Description The ticker symbol (unique identifier) of the instrument. The highest bid price. The lowest ask price. The price at which the last trade was executed. The quantity of the last trade. The volume on the bid price in the exchange order book. The volume on the ask price in the exchange order book. The date of the expiration of the instrument, if any. Description Sends an order to the exchange. Sends a request to the exchange to cancel an order or orders. 36 4.5. MEMORY MANAGEMENT IN Encapsulation Encapsulation is the process of containing abstracted data and functionalities into a class, exposing to the outside world only those methods that absolutely must be exposed, which are then known collectively as the class public interface. So, classes hide the implementation of their properties and methods and communicate with the external programming environment through the public interface. In this way, encapsulation protects the object from being tampered with and frees the programmer from having to know the details of the object s implementation. In our Instrument class example, because the outside programming environment does not need to be exposed to the method of retrieving the real-time bid or ask price, this functionality is encapsulated and made invisible to the outside world Inheritance Within an automated trading system, we need to represent tradable instruments in code. A futures contract is a tradable instrument, as is a stock or an option. All of these could become objects in our program so we will need to create classes for these. However, all of these are also instances of the Instrument class as we have abstracted it. The Instrument class contains only those properties and methods that are common to all tradable instruments. In order to represent a futures contract in our program, we could create a new Futures class that inherits from the Instrument class. As such, the Futures class would inherit all the properties and methods from the base, or parent, Instrument class. The Futures class then may have some added properties or functionalities that are unique to futures contracts. Likewise, we could create an Option class that inherits from the Instrument class and has its own specific functionalities added on. A derived class can add functionality beyond that of the base class and it can also override methods of its base class, i. e. a derived class may replace a member function definition of the base class with its own new definition. It is important to note that Visual C provides for three types of classes references types, value types, and unmanged types and the abilities and intricasies of inheritance differ among the three types. As you will see, s common type system dictates that all reference types inherit from the base Object class Polymorphism Briefly, polymorphism allows us to have one method name, or function name, used in different derived classes, but yet have different implementations, or functionalities, associated with that name depending on the class. In a CallOption class and a PutOption class, for example, we may have inherited a BlackScholesPrice() method from the parent Option class, but yet each of the derived classes has their own method for calculation, as the equations for Black Scholes call and put pricing are different Memory Management in In, there are four memory spaces managed and unmanaged stacks and managed and unmanaged heaps.

No comments:

Post a Comment