Budowanie zautomatyzowanych systemów transakcyjnych. Wprowadzenie do Visual C 2005 Transcription 2 Budowanie zautomatyzowanych systemów transakcyjnych z wprowadzeniem do Visual C 2005 3 The Financial Market Technology Series Series to platforma współpracy Elsevier, Inc. z Institute for Market Technology. (i4mt) do publikowania najnowocześniejszych książek obejmujących tematy dotyczące integracji technologii z rynkami finansowymi, w tym: zautomatyzowanego handlu, budowania handlu i systemów inwestycyjnych, kwestii operacyjnych w przetwarzaniu back office, rozliczeń i rozliczeń, a kwestie zgodności i zarządzania, gdy dotyczą do technologii. Celem serii jest promowanie lepszego zrozumienia i kompetencji w zakresie technologii w branży finansowej poprzez publikowanie wysokiej jakości książek na temat najnowszych obszarów badań i praktyk dla profesjonalistów pracujących na rynkach finansowych. Redaktor serii: Ben Van Vliet jest wykładowcą i zastępcą dyrektora mgr inż. w programie rynków finansowych w Stuart Graduate School of Business, Illinois Institute of Technology. W ramach tego programu prowadzi kursy dla absolwentów w zakresie finansów ilościowych i automatycznego rozwoju systemów transakcyjnych przy użyciu Visual Basic, SQL, XML, ISO C oraz Visual C i UML. Jest także współtwórcą TraderDNA, pakietu oprogramowania do oceny wydajności handlu w czasie rzeczywistym, a także jest dyrektorem TraderDNA LLC. Pełni również funkcję Wiceprezesa Instytutu Technologii Rynku (i4mt), organizacji non-profit, która zapewnia programy edukacyjne na rynkach finansowych i technologii, gdzie jest także przewodniczącym Komitetu ds. Technologii Rynku dla programu CTSD (Certified Trading System Developer). Zobacz więcej informacji. Pan Van Vliet prowadzi również szerokie konsultacje w branży finansowej. Jest autorem Automatyzowanych Systemów Handlowych Budynków (Academic Press, 2007) oraz współautorem Modeling Financial Markets (McGraw-Hill 2004). Czekamy na propozycje książek do serii. Proszę przejść do miejsca, w którym znajduje się link do przesłania nam oferty. 4 Budowanie zautomatyzowanych systemów handlu Wprowadzenie do Visual C 2005 Benjamin Van Vliet AMSTERDAM BOSTON HEIDELBERG LONDYN NEW YORK OXFORD PARIS SAN DIEGO SAN FRANCISCO SINGAPUR SYDNEY TOKYO Academic Press to odcisk Elsevier 5 Academic Press to odcisk Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, USA 525 B Street, Suite 1900, San Diego, Kalifornia. USA 84 Theobald s Road, London WC1X 8RR, Wielka Brytania Ta książka jest drukowana na papierze bezkwasowym. Copyright 2007, Elsevier Inc. Wszelkie prawa zastrzeżone. Żadna część tej publikacji nie może być powielana ani przesyłana w żadnej formie ani żadnymi środkami, elektronicznymi lub mechanicznymi, w tym kserokopią, nagrywaniem lub jakimkolwiek systemem przechowywania i wyszukiwania informacji, bez pisemnej zgody wydawcy. Pozwolenia można uzyskać bezpośrednio w Elsevier's Science amp Technology Rights Department w Oksfordzie, w Wielkiej Brytanii: telefon: (44). faks: (44). Możesz również wypełnić swoje żądanie on-line za pośrednictwem strony domowej Elsevier (elsevier), wybierając opcję Support amp Contact, a następnie Copyright i Permission, a następnie Uzyskiwanie uprawnień. Biblioteka Kongresu Katalogowanie w publikacji Dane Van Vliet, Benjamin Budowanie automatycznych systemów transakcyjnych. z wprowadzeniem do Visual C 2005 Benjamin Van Vliet. str. cm. Obejmuje odniesienia bibliograficzne i indeks. ISBN (papier wartościowy) 1. Elektroniczny obrót papierami wartościowymi. 2. Finansowanie modeli matematycznych. 3. Microsoft Visual C Microsoft. I. Tytuł. HG V dc British Library Cataloging-in-Publication Data Rekord katalogu dla tej książki jest dostępny w British Library. ISBN 13: ISBN 10: Informacje na temat wszystkich publikacji prasowych Academic można znaleźć na naszej stronie internetowej pod adresem Printed w Stanach Zjednoczonych 6 Spis treści Podziękowania xiii ROZDZIAŁ 1 Wprowadzenie Struktura ISO niniejszej książki 2 Rozdział I: Wprowadzenie do programu Visual C 2005 ROZDZIAŁ 2 Framework MS Visual Studio 2005 Struktura projektu Co to jest CCLI Dlaczego Visual C Kompilator VC Co na temat szybkości Kod przykładowy kodu: MessageBoxExample Przykładowy kod: StringConcatExample Przykładowy kod: DebugExample Podsumowanie wyników 14 ROZDZIAŁ 3 Śledzące odniesienia Przykładowy kod: TrackingReferenceExample Przykładowy kod: TemplateFunctionExample Managed Handle Przykładowy kod: Ref TypPrzykład Podsumowanie 17 v 7 vi Spis treści ROZDZIAŁ 4 Klasy i obiekty Abstrakcja Enkapsulacja Dziedziczenie Polimorfizm Zarządzanie pamięcią w typach NET Rodzaje niezarządzane Mieszane zespoły Podsumowanie 23 ROZDZIAŁ 5 Typy referencyjne Przykładowy kod: Ref TypPrzykład Usuń i ułóż Finalizuj Przykładowy kod: FinalizeExample Stack Semantics dla typów ref. Nullptr Reference T jego jest Ważne Podsumowanie 31 ROZDZIAŁ 6 Typy wartości Przykładowy kod: ValueTypesExample Przykładowy kod: PassingValueTypesExample Podsumowanie 36 ROZDZIAŁ 7 Niezabezpieczone obiekty Przykładowy kod: UnmanagedObjectExample Podsumowanie 39 ROZDZIAŁ 8 Składowy kod próbki: CompositionExample Przykładowy kod: UnmanagedCompositionExample Przykładowy kod: ManagedCompositionExample Podsumowanie 48 ROZDZIAŁ 9 Właściwości Przykład Kod: PropertiesExample Summary 50 ROZDZIAŁ 10 Struktury i enumeracje Przykładowy kod: ValueStructureExample Przykładowy kod: ReferenceStructureExample Przykładowy kod: EnumsPrzykład Podsumowanie 53 8 Spis treści vii ROZDZIAŁ 11 Modyfikatory dostępu do dziedziczenia Klasa obiektu Klasa abstrakcyjna i zapieczętowana Kod przykładowy: Dziedziczenie Przykłady interfejsów Przykładowy kod: InterfaceExample Runtime Callable Podsumowanie opakowania 60 ROZDZIAŁ 12 Konwersja i casting Konwersja przykładowego kodu: ConvertExample Statyczny casting Przykładowy kod: StaticCastExample Dynamic Casting Przykładowy kod: DynamicCastExample Safe Casting Przykładowy kod: SafeCastExample Podsumowanie 65 ROZDZIAŁ 13 Przeciążenie operatora Kod przykładowy: OpOverloadEprzykład Podsumowanie 69 ROZDZIAŁ 14 Delegowane i zdarzenia Delegowane przykładowy kod: Delegowany Przykład Sample Multicasting Przykładowy kod: MulticastExample Wydarzenia Przykładowy kod: EventExample Wrappers Przykładowy kod: WrapperExample Wywołania metod asynchronicznych Przykładowy kod: AsynchEventExample Podsumowanie 82 ROZDZIAŁ 15 Tablice Przykładowy kod: ManagedArrayExample Sample Kod: PassingArraysExample Podsumowanie 85 vii 9 viii Spis treści ROZDZIAŁ 16 Generowanie losowych liczb Przykładowy kod: przypadkowy Przykładowy kod: StdNormRandomExample Podsumowanie 89 ROZDZIAŁ 17 Czas i timery Przykładowy kod: Milisekund Przykładowy kod Stoper Przykładowy kod: StoperExample Timery Przykładowy kod: FormsTimerExample Przykładowy kod: ThreadingTimerExample Przykładowy kod: TimersTimerExample Podsumowanie 98 ROZDZIAŁ 18 Strumienie wejściowe i wyjściowe Klasa FileStream Klasa plików StreamWriter i klasy katalogów Klasa aplikacji Kod kwerendy FileMode Przykład: StreamWriterExample Przykładowy kod: StreamReaderExample Podsumowanie 101 ROZDZIAŁ 19 Exception Handl Kod przykładowy: wyjątki Przykładowy kod catching niezarządzanego typu C Podsumowanie 105 ROZDZIAŁ 20 Zbiory Przykładowy kod: HashtableExample Sorted List Class Sample Code: SortedListExample GenericsExample Thread Sample Code: LinkedListExample Przykładowy kod: GenericsExample Podsumowanie 112 ROZDZIAŁ 21 STLSTL Przykładowy kod: STLExample Przykładowy kod: STLExample Podsumowanie 114 10 Spis treści ix ROZDZIAŁ 22 Zbiory danych Przykładowy kod: wiersze danych DataSetExample, zestaw rekordów danych i zestawienie danych Podsumowanie 117 ROZDZIAŁ 23 Łączenie z bazami danych Dane połączenia z bazą danychAdapter Przykładowy kod: Wyliczanie wartości ADO za pomocą wszystkich danych w zestawie danych Korzystanie z programu Excel jako źródła danych Zapisywanie danych XML z zestawu danych Aktualizowanie bazy danych ze zmianami w zestawie danych Pobieranie danych za pomocą modułu DataReader Podsumowanie 124 ROZDZIAŁ 24 Strukturalny język danych Język manipulacji Aktualizacja bazy danych ze zmianami w definicji danych DataSet Podsumowanie języka 140 ROZDZIAŁ 25 Dobrze sformułowane dokumenty XML Poprawne dokumenty XML Schemat XML Dokumenty Parsery Przykładowy kod: T raders. xsd Przykładowy kod: XmlWriterExample Przykładowy kod: XmlReaderExample Podsumowanie 146 ROZDZIAŁ 26 Informacje finansowe Protokół wymiany Protokoły XML na rynkach finansowych Omówienie podsumowania FIX 151 ROZDZIAŁ 28 Serializacja Serializacja Podsumowanie przykładu 154 ROZDZIAŁ 28 Usługi Windows Przykładowy kod: WindowsServiceExample Podsumowanie 159 11 x Spis treści ROZDZIAŁ 29 Pakiety instalacji i instalacji Przykładowy kod: Instalacja Podsumowanie przykładu 162 Sekcja II: Współbieżność ROZDZIAŁ 30 Nawlekanie wątku Przestrzeń nazw Przykładowy kod: Wątek Przykładowy kod: Wątek Przykład Przykładowy wątek Przykładowy kod: Wątek Priorytet Przykład Stopień wyliczeniowy ThreadPool Przykładowy kod klasy: ThreadPoolExample Aktualizowanie formularzy z innych wątków Przykładowy kod: FormUpdateExample Podsumowanie bezpieczeństwa wątków 175 ROZDZIAŁ 31 Synchronizacja Klasy Przykładowy kod: SynchronizeExample Klasa Mutex Przykład Kod: MutexExample Semaphore Class Sample Code: SemaphoreExample Monitor Class Sample Code: Monitor Summary 182 ROZDZIAŁ 32 Gniazda Przykładowy kod: SynchronousServerExample Przykładowy kod: SynchronousClientExample Podsumowanie 189 Rozdział III: Interoperacyjność i łączność ROZDZIAŁ 33 Marshaling Marshal Class Sample Code: StringToCharArrayExample Podsumowanie 194 ROZDZIAŁ 34 Wskaźniki wewnętrzne i pinezki Przykładowy kod: InteriorPointerExample Wskaźniki przypinania Przykładowy kod: Przypinanie Przykład Podsumowanie 198 12 Spis treści xi ROZDZIAŁ 35 Podłączanie do zarządzanego Pliki DLL Przykład Kod: DLLExample Podsumowanie 201 ROZDZIAŁ 36 Łączenie się z plikami DLL Component Object Model (COM) z COM Interop Przykład Kod: MyCOMLibrary Przykładowy kod: UsingCOMDLLExample Podsumowanie 207 ROZDZIAŁ 37 Łączenie się z bibliotekami DLL C za pomocą wywołań platformy Usługi wywoływania funkcji w stylu C Przykładowy kod: MyWin32Library Przykładowy kod: UsingWin32DLLExample Tworzenie obiektów Przykładowy kod: MyWin32ClassLibrary Przykładowy kod: UsingWin32ClassExample CallingConventionEnumeration Summary 216 ROZDZIAŁ 38 Łączenie z Excel Przykładowy kod: ControllingExcelExample Przykładowy kod: ExcelChartExample Podsumowanie 221 ROZDZIAŁ 39 Łączenie z Trad erAPI Przegląd TraderAPI FillObj InstrObjClass InstrNotifyClass OrderObj OrderProfi leclass OrderSetClass Przykładowy kod: TraderAPIConnectionExample Podsumowanie 230 ROZDZIAŁ 40 Podłączanie do XTAPI Przykładowy kod: XTAPIConnectionExample Podsumowanie 233 13 xii Spis treści Rozdział IV: Automatyczne systemy transakcyjne ROZDZIAŁ 41 Budowanie systemów transakcyjnych Buy vs. Build Data Mapping Prędkość rozwoju Dziesięć rzeczy, które wpływają na szybkość systemu transakcyjnego. Poprawia się logika Wyciek Dziesięć rzeczy, które wpływają na podatność Profesora na system transakcyjny Podsumowanie 245 ROZDZIAŁ 42 Metodologia opracowywania systemu obrotu KV Analiza dokumentów pieniężnych i dokumentów Wstecz Testuj narzędzie Zarządzaj portfelem i podsumowuj ryzyko 257 ROZDZIAŁ 43 Zautomatyzowane systemy systemu handlu Klasy Instrument Klasy Klasyfikacja Księga zamówień Klasyfikacja Tick lub Pasek zbierania paska Menedżer systemu Podsumowanie graficznego interfejsu użytkownika 265 ROZDZIAŁ 44 System z pojedynczym gwintem, system analizy technicznej Kod przykładowy: TechincalSystemExample Podsumowanie 277 ROZDZIAŁ 45 ProducerConsum er Wzór wzoru Przykładowy kod: ProducerConsumerEample Przykład Podsumowanie 287 ROZDZIAŁ 46 Wielowątkowy, statystyczny system arbitrażowy Przykładowy kod: SpreaderPrzykład Podsumowanie Wnioski 304 14 Podziękowania Niniejsza książka zaczęła się jako notatka dla nauczyciela w Instytucie Technologii w Illinois pod nazwą Advanced Object Oriented Programming for Financial Rynki. W tej klasie zajmujemy się projektowaniem i rozwojem zautomatyzowanego systemu transakcyjnego przy użyciu Microsoft Visual C. Kiedy zacząłem nauczać ten kurs kilka lat temu, nie mogłem znaleźć książki, która obejmowałaby wszystkie tematy niezbędne do budowy automatycznych systemów transakcyjnych w czasie rzeczywistym, a więc w związku z tym książka stara się skupić na zagadnieniach programowania i technologii związanych z rozwojem selekcji handlu, rutowania zamówień, zarządzania zamówieniami i algorytmów zarządzania pozycjami. Mam nadzieję, że więcej szkół będzie oferować kursy na temat automatycznego projektowania systemów transakcyjnych w przyszłości i że ta książka będzie pomocna w ich instrukcjach. Co więcej, ta książka jest tekstem podstawowym do programu CTSD Certified Trading System Developer oferowanego przez Institute for Market Technology (i4mt. org). Jest to nowy program certyfikacji, który składa się z trzech egzaminów, jednego w zakresie finansów ilościowych, jednego w zakresie papierów wartościowych i strategii handlu instrumentami pochodnymi, oraz jednego w zakresie programowania i technologii rynkowej ISO CC. Ten rygorystyczny program samokształcenia ma na celu połączenie umiejętności potrzebnych w branży finansowej. Kandydaci, którzy uzyskają oznaczenie CTSD będą rzeczywiście utalentowanymi ludźmi. Jak można sobie wyobrazić, dodatkowe podziękowania za ukończenie tego projektu muszą zostać udzielone wielu przyjaciołom, rodzinie i współpracownikom: w szczególności mojej żonie, Julii, Markowi McCrackenowi, dr Andrew Kumiedze, Andrew Acosta, Sagyemu Mintzowi, Jasonowi Malkinowi, 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 i wszyscy moi koledzy z Centrum IIT dla rynków finansowych Russell Wójcik, dr Michael Gorham, Keith Black, dr Michael Ong, dr John Bilson, dr Michael Kelly i Jodi Houlihan. Chciałbym również podziękować wielu studentom, którzy wzięli udział w kursie i udzielili cennych informacji zwrotnych. Bez ich pomocy i pomocy wielu innych książka ta nigdy by nie została ukończona. xiii 15 xiv Podziękowania Niniejsza książka została napisana dla osób znających ISO C lub prawdopodobnie Java lub COM. Dla inżynierów finansowych i początkujących inżynierów finansowych o ogólnym doświadczeniu programistycznym książka ta będzie zawierać dogłębną dyskusję na temat koncepcji programowania na wyższym poziomie, takich jak obsługa zdarzeń, interoperacyjność, łączność danych i współbieżność. Dla doświadczonych programistów C, może się okazać, że ta książka stanowi dobre wprowadzenie do używania C w ramach. Niezależnie od przypadku, mam nadzieję, że czerpiesz z niego naukę i jesteś zainspirowany do głębszego zagłębiania się w temat rozwoju automatycznego systemu transakcyjnego. Prześlij mi wszelkie opinie. Zobowiązuję się do aktualizacji mojej strony internetowej, regularnie z poprawkami do erraty i dodatkowymi przykładami. 16 ROZDZIAŁ 1 Wprowadzenie Zautomatyzowane (lub algorytmiczne) systemy transakcyjne składają się z wielu części, zarówno klientów sprzętu i oprogramowania, serwerów, sieci, baz danych, silników obliczeniowych, interfejsów programowania aplikacji, plików danych w czasie rzeczywistym, jak i graficznych interfejsów użytkownika. Jednak logika biznesowa systemów transakcyjnych, która składa się z algorytmów wyboru transakcji, zarządzania zamówieniami i logiki zarządzania pozycjami, jest zawarta w oprogramowaniu, a książka ta dotyczy hermetyzacji logiki biznesowej systemu handlu w oprogramowaniu kontrolującym przepływ rynku dane. (W książce tej nie ma danych ilościowych.) Zautomatyzowany system handlu składa się z reguł wejścia i wyjścia z pozycji lub pozycji oraz technologii, zarówno sprzętu, jak i oprogramowania, w celu ich realizacji. Reguły te są zestawem operacji logicznych lub matematycznych, które mogą być oparte na badaniach jakościowych, technicznych lub ilościowych. Jeśli chcemy zbudować zautomatyzowany system, który wykonuje transakcje na elektronicznych giełdach, musimy nauczyć się, jak pracować z danymi, zarówno danymi rynkowymi w czasie rzeczywistym, jak i danymi historycznymi, w kodzie. Przecież dane są siłą napędową rynków elektronicznych, według Davida Normana w jego książce Professional Electronic Trading. O to właśnie chodzi w tej książce, używając Visual C do zarządzania danymi rynków finansowych (i jest ich dużo) w aplikacjach systemu transakcyjnego. Ogólnie mówiąc, niniejsza książka obejmuje trzy rzeczy: 1. Zarządzanie danymi w pamięci. 2. Przechowywanie danych i pobieranie z baz danych. 3. Przekazywanie danych. Programowanie front office na rynkach finansowych w dużej mierze dotyczy podłączania do baz danych, kanałów danych w czasie rzeczywistym, platform do realizacji zleceń, bibliotek kwantowych, silników optymalizacyjnych, oprogramowania do tworzenia wykresów, silników generujących raporty, starszych technologii i Excela, by wymienić tylko kilka. Aby skutecznie zarządzać danymi w czasie rzeczywistym i danymi historycznymi, musimy zrozumieć: 1. Architektura sterowana zdarzeniami. 2. Współbieżność. 3. Łączność i interoperacyjność. 1 17 2 ROZDZIAŁ 1 Wprowadzenie Ta książka zawiera dziesiątki ważnych zagadnień technologicznych, z którymi zmierzysz się podczas budowy automatycznych systemów transakcyjnych w świecie rzeczywistym, ale nie pokazuje, w jaki sposób zbudować rentowny system transakcyjny. (Ważne jest jednak, aby przyznać, że przewaga technologiczna może być dużą przewagą konkurencyjną.) Istnieją cztery dyscypliny, które wchodzą w skład automatycznej nauki systemów rozwoju, finansów ilościowych, strategii handlowej i zarządzania jakością, i jest to książka informatyczna. Opracowanie i testowanie metod selekcji i zarządzania ryzykiem są tematami dla innych książek. Ta książka opisuje podstawy tego, co inżynier finansowy powinien wiedzieć o programowaniu w obiektach, SQL, wielowątkowość, interoperacyjność, komunikatory, algorytmy wyboru zamówień i techniki zarządzania zamówieniami. W tym tekście próbowałem uwzględnić informacje kierowane przez rynek i związane z pracą. Dzisiejsi pracodawcy na rynkach finansowych wymagają gotowości do pracy. Jeśli chcesz dostać pracę w branży handlu i zarządzania pieniędzmi, która coraz częściej jest napędzana przez zautomatyzowane systemy, musisz mieć konkurencyjny poziom znajomości programowania. Powinieneś sobie jednak uświadomić, że ta książka jest przeglądem. Nie nauczy cię wszystkiego. Technologia jako temat jest oczywiście zbyt obszerna, by ją objąć w jednej książce. Nawet zawężenie go do VC dla rozwoju systemu transakcyjnego jest nadal zbyt rozległe. Na stronach przedstawię kilka ważnych pomysłów, postaram się wskazać ci właściwy kierunek i, miejmy nadzieję, w końcu zainspiruję Cię do przeprowadzenia dodatkowych badań na temat rozwoju automatycznego systemu handlu. Odtąd staranny inżynier finansowy musi dalej badać swoją własną ISO C Ta książka obejmuje aspekty programowania rozwoju systemu handlu i zakłada, że znasz pojęcia programowania ISO C, w tym wskaźniki, funkcje, obiekty i szablon standardowy Struktura biblioteki tej książki Zautomatyzowane systemy transakcyjne znajdują swoją najczystszą formę w strategiach wysokiej częstotliwości, w których szybkość obliczeń i realizacji jest przewagą konkurencyjną. Inne systemy, w których milisekundy niekoniecznie są istotne, mogą być w pełni zautomatyzowane lub częściowo zautomatyzowane. Niniejszy tekst skupi się na wprowadzeniu koncepcji programowania i projektowania systemów o wyższej częstotliwości. Omówienie wszystkich alternatywnych koncepcji technologicznych projektowania systemu handlu i prezentacji kompletnego systemu handlu wykracza poza zakres książki. Systemy handlu przedstawione w tej książce są drastycznie uproszczone, aby zilustrować wspólne koncepcje programowania i projektowania. Ta książka jest podzielona na cztery sekcje. Pierwsza sekcja koncentruje się wyłącznie na wprowadzeniu do typów Visual C i technik programowania. Druga sekcja koncentruje się na wielowątkowości. Trzeci koncentruje się na interoperacyjności i łączności, a czwarty na obiektach, wzorach projektowych i koncepcjach architektonicznych dla rozwoju automatycznego systemu handlu. Na koniec, po prostu przeczytanie tej książki nie sprawi, że będziesz ekspertem. Aby naprawdę poznać materiał z tej książki, powinieneś także przejrzeć przedstawione przykłady kodu. Tylko poprzez zaangażowanie się w proces, a ponadto wyjście poza niego, zyskasz zrozumienie i intuicję. To ciężka praca, ale się opłaci. 18 SEKCJA I Wprowadzenie do Visual C 2005 19 Strona celowo pozostawiona pusta 20 ROZDZIAŁ 2 Struktura 2.1. MS Visual Studio 2005 Struktura projektu W MS Visual Studio 2005 twoja aplikacja nazywa się rozwiązaniem, a rozwiązaniem może być jeden lub więcej projektów, w których każdy projekt może znajdować się w innym języku Visual Studio. W trakcie tej książki przedstawię rozwiązania opracowane w większości w MS Visual C dla zarządzanych lub aplikacji z powodów, które wyjaśnię wkrótce. Należy jednak pamiętać, że Visual C nie jest nowym językiem programowania, ale raczej pełnym środowiskiem programistycznym zapewniającym zwiększoną obsługę wielu typów projektów C, w tym: projektów Active Template Library (ATL). Projekty MS Foundation Classes (MFC). lub zarządzane projekty konsolowe, Windows lub DLL. Win32 Console dla projektów ISO C. Projekty Win32 i biblioteki DLL. W rezultacie Visual C dla lub zarządzanych projektów jest tylko jednym z kilku języków C oferowanych w Visual Studio 2005, i jest to jedna z rzeczy, która odróżnia nowy VC od innych w rodzinie zapewnia zasadniczo pięć niezależnych języków C jeden pakiet. Jeśli chcesz kontynuować tworzenie aplikacji MFC, możesz to zrobić tak jak wcześniej. W rzeczywistości obsługa MFC i ATL została poprawiona w VS W poprzednich wersjach Visual Studio rozszerzenie zostało dodane do nazwy w celu odróżnienia go od wcześniejszych wersji, takich jak Visual Basic 6.0. Wraz z nadejściem VS 2005, rozszerzenie nazwy jest zwykle pomijane i możemy nazywać je VB, C i Visual C Co to jest CCLI CCLI (Common Language Infrastructure) jest pochodną C. Według Stanleya Lippman'a Microsoft: 5 21 6 ROZDZIAŁ 2 Struktura CLI dotyczy architektury Common Language Infrastructure, wielowarstwowej architektury obsługującej dynamiczny model programowania komponentów. Pod wieloma względami stanowi to całkowite odwrócenie modelu obiektu C. Warstwa oprogramowania uruchomieniowego, wirtualny system wykonawczy, działa między programem a bazowym systemem operacyjnym. Dostęp do maszyny bazowej jest dość ograniczony. Dostęp do typów aktywnych w programie wykonawczym i związanej z nimi infrastruktury programowej, zarówno pod względem wykrywania, jak i konstrukcji, jest obsługiwany. Ukośnik () reprezentuje powiązanie między C a CLI. Pierwszym przybliżeniem odpowiedzi na pytanie o to, co jest CCLI, jest to, że jest to wiązanie statycznego modelu obiektów C z dynamicznym modelem obiektu komponentu CLI. Mówiąc krótko, w ten sposób programujesz za pomocą C zamiast C lub Visual Basic. Podobnie jak C i CLI, CCLI przechodzi normalizację w ramach Europejskiego Stowarzyszenia Producentów Komputerów (ECMA), a ostatecznie w ramach ISO. Środowisko wykonawcze wspólnego języka (CLR) to wersja CLI dla Microsoft, która jest specyficzna dla systemu operacyjnego Windows. Podobnie, Visual C jest implementacją CCLI. Jako drugie przybliżenie odpowiedzi, CCLI integruje model programowania wewnątrz C w taki sam sposób, jak z powrotem w Bell Laboratories, zintegrowaliśmy ogólne programowanie przy użyciu szablonów w istniejącym wówczas C. W obu tych przypadkach twoje inwestycje w istniejącą bazę kodów C i w twojej obecnej wiedzy C są zachowane. Było to niezbędne podstawowe wymaganie projektu CCLI. W trakcie tej książki po prostu odwołuję się do implementacji CCLI Microsoftu jako Visual C. Pełen artykuł pana Lippman, przejdź do msdnmagissues0600purecdefault. aspx Dlaczego Visual C Dlaczego Visual C Jakie są zalety aplikacji zarządzanych lub C Po prostu i, w słowach wiceprezesa głównego dostawcy oprogramowania transakcyjnego tutaj, w Chicago, NET jest przyszłością. Co najważniejsze, Framework zawiera wiele klas, które pomagają w rozwoju systemów handlu, jak zobaczymy. Ponadto, w porównaniu do innych języków, VC zawiera znacznie większe wsparcie dla interoperacyjności między kodem zarządzanym i niezarządzanym. Ponadto na rynkach finansowych konieczna jest interoperacyjność. W VC mamy dokładną kontrolę nad zarządzanymi i niezarządzanymi alokacjami sterty i stosu oraz zarządzanym i niezarządzanym kodem, a wszystkie mogą istnieć płynnie w tym samym projekcie. Dzięki temu możemy szybko i łatwo zintegrować nasze istniejące aplikacje C, funkcje i obiekty w nowe aplikacje. Jest to szczególnie ważne w przypadku aplikacji COM, które są często wykorzystywane w branży finansowej i nie są zarządzane. Ponadto, jeśli masz biblioteki obiektów lub funkcji finansowych zapisanych w natywnym C, VC z obszerną zarządzaną niedziałającą obsługą interopów da ci ogromną kontrolę. Ewentualnie, jeśli masz już aplikacje C, do których chcesz się przekonwertować, ponownie VC dostarczy Ci narzędzia, których nie będą mogły używać inne języki. Wreszcie, chociaż wersja STL z 2005 roku (znana jako STL) nie jest jeszcze dostępna, wkrótce nastąpi konwersja natywnego kodu zależnego od STL. 22 2.6. RAMY Kompilator VC Oto kilka rzeczy do zapamiętania na temat kompilatora VC. Kompilator VC, C1.exe, używa rozszerzenia the. c do kompilacji C-and. cpp dla C i C. Również standardowe nagłówki nie wymagają rozszerzenia. h, ponieważ Microsoft zawarł własne wersje tych plików w przestrzeń nazw standardu. Ponadto, okno właściwości projektu wyświetla wszystkie ustawienia kompilatora dla CC, w tym linker i zdarzenia kompilacji. Kompilator Microsoft s Cl. exe implementuje standardy ANSI C i ISO C i jest zgodny z 98C zgodnie z Microsoft. Kompilator oferuje Konfiguracje rozwiązań do kompilacji debugowania i kompilacji wersji. Dzięki kompilacji debugowania możemy wchodzić w interakcję z naszym kodem w czasie wykonywania. To duża pomoc. Jednak nie dokonano optymalizacji, a do tego używamy wersji Release, która wygeneruje szybszy, zoptymalizowany kod. Kompilator pozwala nam włączyć natywny kod C do naszych projektów i najpierw kompiluje się w Microsoft Intermediate Language (MSIL). Następnie MSIL jest konwertowany na kod natywny przez kompilator Just In Time (JIT). W JIT niektóre operacje będą szybsze niż natywne C, podczas gdy inne będą wolniejsze. W wyniku tego powstają kompromisy między szybkością rozwoju a szybkością wykonania. Są jednak rzeczy, które możemy zrobić, aby zminimalizować koszty niektórych operacji. Kompilator VC i JIT można dostroić, aby wygenerować najszybszy możliwy kod przy użyciu dostępnych opcji kompilatora. Jeśli poważnie myślisz o prędkości, poświęć trochę czasu, aby zbadać dalszy kompilator VC Microsoftu. Co, oczywiście, o prędkości prędkości jest ważne. W celu dogłębnej dyskusji na temat szybkości w zarządzanym kodzie, odniosę się do kilku doskonałych artykułów w bibliotece MSDN (msdn. microsoft. Comlibrary): A Baker's Dozen: trzynaście rzeczy, które powinieneś wiedzieć przed przeniesieniem twoich programów Visual C do Visual Studio 2005, Stanley Lippman. Najlepsze metody pisania wydajnego i niezawodnego kodu z CCLI autorstwa Kenny'ego Kerra. C: Najpotężniejszy język programowania ramowego Kenny'ego Kerra. Pisanie szybszego kodu zarządzanego: Know What Things Koszt Jan Gray. Pisanie wysokowydajnych aplikacji zarządzanych: elementarz Gregora Noriskina (zawiera przegląd profilu CLR). Wskazówki dotyczące ulepszania kodu czasowo krytycznego. Optymalizacja Najlepsze praktyki w sekcji Visual C Framework Podczas tworzenia zarządzanych aplikacji Visual C nasze programy są opracowywane, kompilowane i wykonywane w ramach Framework. Struktura składa się z trzech części: 23 8 ROZDZIAŁ 2 Ramy 1. Wspólne środowisko językowe (CLR). 2. Biblioteki klas. 3. ASP. ASP to platforma programistyczna Microsoftu służąca do tworzenia korporacyjnych aplikacji internetowych, które działają zbyt wolno w czasie rzeczywistym, aplikacje rynków finansowych, więc nie będziemy poświęcać czasu na jej zbadanie. Zamiast tego poświęcimy czas na poznanie wspólnego środowiska uruchomieniowego języka i bibliotek klas oraz sposobu, w jaki możemy wykorzystać je do tworzenia aplikacji finansowych, które mogą potencjalnie działać w wielu systemach operacyjnych, nie tylko w systemie Windows, w tym w systemach Unix, Linux i Mac Common Language Runtime The CLR napędza wykonywanie kodu w ramach programu ramowego i zapewnia programy oparte na integracji języków, zabezpieczeniach, dynamicznym zarządzaniu pamięcią i usługami debugowania. Ponadto CLR kontroluje to, co nazywamy kodem zarządzanym, który jest wykonywany w zarządzanej stercie. Oznacza to, że zarządzana sterta jest kontrolowana przez Framework, a nie system operacyjny. Kod niezarządzany (lub nie kodowany) jest jednak kontrolowany przez system operacyjny. CLR zapewnia również dynamiczne zarządzanie pamięcią za pomocą garbage collector do zarządzania alokacją i dealokacją przestrzeni pamięci, eliminując typowe problemy z wyciekami pamięci, które często występują w oprogramowaniu. Przydzielanie pamięci CLR do zarządzanej sterty jest, jak się okazuje, szybsze niż niezarządzane przydzielanie sterty i prawie tak szybkie, jak przydzielanie pamięci stosu, ponieważ alokuje przyległe lokalizacje w pamięci, po prostu zwiększając wskaźnik. W przypadku kompilator najpierw kompiluje zarządzany kod źródłowy do MSIL. Przed uruchomieniem kodu MSIL jest konwertowany przez kompilator JIT (just-in-time) specyficzny dla architektury komputera. JIT konwertuje język MSIL na język maszynowy lub kod natywny w środowisku Runtime Garbage Collection Odśmiecacz określa najlepszy czas na wykonanie zbioru obiektów bez odwołań. Śmieciarz zwalnia obszar pamięci przydzielony obiektom, które nie są już przywoływane (lub wskazywane) w aplikacji. Framework utrzymuje listę aktywnych odniesień, które utrzymuje kompilator JIT i CLR. Śmieciarz używa tej listy do sprawdzenia wszystkich referencji aplikacji. Obiekty, których nie ma na liście, są uważane za nieosiągalne, a pamięć zostanie zwolniona. W wyniku tego garbage collector analizuje zarządzaną stertę i znajduje bloki przestrzeni zajmowane przez obiekty bez odwołań. W tym samym czasie przywoływane lokalizacje pamięci są zagęszczane i przenoszone oraz wykonywane są niezbędne aktualizacje odniesień do wskaźnika. Ważne jest, aby pamiętać, że śmieciarz będzie poruszał przedmioty w pamięci bez naszej wiedzy. Ma to ważne następstwa w późniejszym czasie Złożenia Zgromadzeń tworzą fundamentalne elementy składowe Ram i każdej aplikacji opracowanej w ramach Zespołów. Zespoły najczęściej istnieją jako pliki wykonywalne lub pliki bibliotek dołączanych dynamicznie i zawierają grupy klas, które tworzą logiczną jednostkę funkcjonalną. 24 2.7. KOD PRZYPADKU: MESSAGEBOXEXAMPLE 9 Zespoły zawierają informacje o zawartości, wersjach i zależnościach, w wyniku czego aplikacje tworzone za pomocą Visual C nie muszą polegać na wartościach rejestru, aby działały poprawnie. Ponieważ rejestr nie jest wymagany, możemy na ogół instalować aplikacje Visual C, po prostu kopiując katalog wykonywalny na komputer docelowy Przestrzenie nazw Przestrzeń nazw organizuje tysiące klas w bibliotekach, zapobiega niejednoznaczności i upraszcza odniesienia, jak zobaczymy. (Programy VC, które piszemy, będą często zawierać lub używać wielu przestrzeni nazw). W systemie przestrzeń nazw jest głównym obszarem nazw i zawiera podstawowe typy danych i podstawowe klasy, takie jak obiekt (z którego wyprowadzane są wszystkie obiekty), łańcuch, wyjątek i śmieci. klasa kolekcjonerska, GC. Dokumentacja programu Visual Studio (pliki pomocy) zawiera stronę odniesienia biblioteki klas Framework, która zawiera obszerną listę obszarów nazw z opisami. Ponieważ całe programowanie zależy od obiektów zawartych w tych przestrzeniach nazw, możesz chcieć poświęcić trochę czasu na zapoznanie się z różnymi przestrzeniami nazw i typami obiektów, które zawierają W pełni kwalifikowane nazwy Podczas korzystania z bibliotek, możemy tworzyć instancje obiektów zdefiniowanych w zewnętrznych lokalizacjach. o ile dodamy odniesienie do złożenia, a następnie użyjemy w pełni kwalifikowanej nazwy klasy w naszym kodzie. Pełna nazwa to odwołanie do klasy, które jest poprzedzone nazwą przestrzeni nazw. 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. Kliknij OK. 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. Ale jest z naszymi algorytmicznymi strategiami handlowymi. Nie wydaje się to możliwe. Jeden algorytmiczny system transakcyjny z tak dużą identyfikacją trendów, analizą cyklu, przepływami po stronie kupna, wieloma strategiami handlowymi, dynamicznym wejściem, ceną docelową i stopową oraz ultraszybką technologią sygnału. Ale to jest. W rzeczywistości AlgoTrades platforma systemu handlu algorytmicznego jest jedyna w swoim rodzaju. Koniec z szukaniem gorących zapasów, sektorów, towarów, indeksów lub opinii na temat rynku czytelnictwa. Algotrades wykonuje wszystkie wyszukiwania, terminy i transakcje za Ciebie, korzystając z naszego algorytmicznego systemu transakcyjnego. Sprawdzone strategie AlgoTrades można śledzić ręcznie poprzez otrzymywanie powiadomień e-mailem i SMS-em lub może to być 100-godzinny handel, a Ty możesz wyłączyć automatyczny handel on-off w dowolnym momencie, dzięki czemu zawsze będziesz mieć kontrolę nad swoim przeznaczeniem. Zautomatyzowane systemy transakcyjne dla doświadczonych inwestorów Copyright 2017 - ALGOTRADY - Zautomatyzowany algorytmiczny system handlu Reguła CFTC 4.41 - HIPOTETYCZNE LUB SYMULOWANE WYNIKI OSIĄGNIĘTE POSIADAJĄ PEWNE OGRANICZENIA. WYOBRAŹ SIĘ DO RZECZYWISTEGO REJESTRACJI WYDAJNOŚCI, SYMULACJA WYNIKÓW NIE REPREZENTUJE RZECZYWISTEGO TRADINGU. RÓWNIEŻ OD OKRESU, W JAKI SPOSÓB TRADY NIE ZOSTAŁY ZOSTAŁY WYKONANE, REZULTATY MOGĄ MIEĆ PONIŻSZE KOMPENSOWANIE W ZAKRESIE WPŁYWU, JEŚLI JAKIEKOLWIEK, NA NIEKTÓRE CZYNNIKI RYNKOWE, TAKIE JAK BRAK PŁYNNOŚCI. SYMULACJA PROGRAMÓW HANDLOWYCH W OGÓLNYM ZAKRESIE PODLEGA WPŁYWIE NA FAKT, KTÓRY ZAPROJEKTOWANO Z KORZYŚCIĄ HINDSIGHT. NIE ZAPEWNIA ŻADNEGO OŚWIADCZENIA, ŻE WSZELKIE RACHUNKI BĘDĄ PRAWDOPODOBNIE OSIĄGNĄĆ ZYSK LUB STRAT PODOBNE PODCZAS TYCH OSÓB. Nie składa się żadnych oświadczeń ani nie sugeruje, że korzystanie z algorytmicznego systemu handlu przyniesie dochód lub zagwarantuje zysk. Istnieje znaczne ryzyko strat związanych z obrotem kontraktami terminowymi i obrotem funduszami giełdowymi. Obrót kontraktami futures i handel giełdowymi funduszami wiąże się ze znacznym ryzykiem strat i nie jest odpowiedni dla wszystkich. Wyniki te są oparte na symulowanych lub hipotetycznych wynikach wydajności, które mają pewne nieodłączne ograniczenia. W przeciwieństwie do wyników pokazanych w rzeczywistych wynikach, wyniki te nie odzwierciedlają faktycznego obrotu. Ponadto, ponieważ transakcje te nie zostały faktycznie zrealizowane, wyniki te mogą być niepełne lub zbytnio skompensowane pod kątem wpływu, jeśli w ogóle, niektórych czynników rynkowych, takich jak brak płynności. Symulowane lub hipotetyczne programy handlowe w ogóle są również uzależnione od tego, czy zostały zaprojektowane z perspektywy czasu. Nie składa się oświadczeń, że jakiekolwiek konto będzie lub może osiągnąć zyski lub straty podobne do tych, które są wykazywane. Informacje na tej stronie zostały przygotowane bez względu na konkretne cele inwestycyjne inwestorów, ich sytuację finansową i potrzeby, a także dalsze doradzanie subskrybentom, aby nie podejmowali żadnych działań, nie uzyskując konkretnej porady od swoich doradców finansowych, aby nie polegać na informacjach ze strony internetowej jako podstawowej zasadzie do podejmowania decyzji inwestycyjnych i do rozważenia własnego profilu ryzyka, tolerancji ryzyka i własnych strat stop. - 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 T his 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 Handl ing 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: T raders. 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 Trad erAPI 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 ProducerConsum er 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. Kliknij OK. 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.
Comments
Post a Comment