Thursday 24 August 2017

Membangun otomatis trading system c ++ net


Membangun Sistem Perdagangan Otomatis. Dengan Pengantar Visual C 2005 Transkripsi 2 Membangun Sistem Perdagangan Otomatis Dengan Pengantar Visual C 2005 3 Editor Seri Seri Teknologi Pasar Keuangan Ben Van Vliet Seri Teknologi Pasar Keuangan adalah kemitraan antara Elsevier, Inc. dan Institute for Market Technology (I4mt) untuk menerbitkan buku-buku mutakhir yang mencakup topik mengenai integrasi teknologi dengan pasar keuangan, termasuk: perdagangan otomatis, membangun sistem perdagangan dan investasi, masalah operasional dalam pemrosesan back office, kliring dan penyelesaian, dan masalah kepatuhan dan tata kelola yang terkait Untuk teknologi. Tujuan dari rangkaian ini adalah untuk meningkatkan pemahaman dan kompetensi dengan teknologi di industri keuangan melalui penerbitan buku berkualitas tinggi mengenai bidang penelitian dan praktik terbaru bagi para profesional yang bekerja di pasar keuangan. Editor Seri: Ben Van Vliet adalah seorang Dosen dan Direktur Associate dari M. Sc. Di Pasar Keuangan Program di Stuart Graduate School of Business, Illinois Institute of Technology. Dalam program ini, ia mengajar kursus pascasarjana dalam pengembangan sistem keuangan kuantitatif dan otomatis dengan menggunakan Visual Basic, SQL, XML, ISO C dan Visual C dan UML. Dia juga merupakan penemu TraderDNA, paket perangkat lunak evaluasi kinerja real-time trading, serta menjadi Direktur di TraderDNA LLC. Dia juga menjabat sebagai Wakil Ketua Institut Teknologi Pasar (i4mt), sebuah organisasi nirlaba yang menyediakan program pendidikan di pasar keuangan dan teknologi, di mana dia juga memimpin Komite Teknologi Pasar untuk program Certified Trading System Developer (CTSD). Silakan lihat informasi lebih lanjut. Van Vliet juga banyak berkonsultasi dalam industri keuangan. Dia adalah penulis Building Automated Trading Systems (Academic Press, 2007) dan rekan penulis Modeling Financial Markets (McGraw-Hill 2004). Kami menyambut proposal untuk buku untuk serial ini. Silakan pergi ke tempat Anda akan menemukan link untuk mengirimkan proposal Anda kepada kami. 4 Membangun Sistem Perdagangan Otomatis Dengan Pengantar Visual C 2005 Benjamin Van Vliet AMSTERDAM BOSTON HEIDELBERG LONDON NEW YORK OXFORD PARIS SAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYO Press akademik adalah jejak Elsevier 5 Academic Press adalah jejak Elsevier 30 Corporate Drive, Suite 400, Burlington, MA 01803, Amerika Serikat 525 B Street, Suite 1900, San Diego, California. USA 84 Theobald s Road, London WC1X 8RR, UK Buku ini dicetak dengan kertas bebas asam. Hak Cipta 2007, Elsevier Inc. Semua hak dilindungi undang-undang. Tidak ada bagian dari publikasi ini yang dapat diproduksi ulang atau dikirim dalam bentuk apapun atau dengan cara apapun, elektronik atau mekanis, termasuk fotokopi, rekaman, atau sistem penyimpanan dan pengambilan informasi, tanpa izin tertulis dari penerbit. Izin dapat dicari langsung dari Elsevier s Science amp Departemen Hak Teknologi di Oxford, Inggris: telepon: (44). Fax: (44). Anda juga dapat melengkapi permintaan Anda secara on-line melalui homepage Elsevier (elsevier), dengan memilih Support amp Contact lalu Hak Cipta dan Izin dan kemudian Mendapatkan Izin. Perpustakaan Kongres Cataloging-in-Publikasi Data Van Vliet, Benjamin Membangun sistem perdagangan otomatis. Dengan diperkenalkannya Visual C 2005 Benjamin Van Vliet. Hal. Cm. Termasuk referensi bibliografi dan indeks. ISBN (alk. Kertas) 1. Perdagangan sekuritas elektronik. 2. Keuangan model matematika. 3. Microsoft Visual C Microsoft. I. Judul HG V dc Data Katalog-in-Publikasi Perpustakaan Inggris Catatan katalog untuk buku ini tersedia di British Library. ISBN 13: ISBN 10: Untuk informasi tentang semua publikasi Pers Akademik kunjungi situs Web kami di Printed in Amerika Serikat 6 Daftar Isi Ucapan Terima Kasih xiii BAB 1 Pendahuluan Struktur ISO C dari Buku Ini 2 Bagian I: Pengantar Visual C 2005 BAB 2 Kerangka MS Visual Studio 2005 Struktur Proyek Apa itu CCLI Mengapa Visual C Kompiler VC Bagaimana dengan Kecepatan Kerangka Contoh Kode: Contoh Kode Contoh: StringConcat Contoh Contoh Contoh: Ringkasan Versi DebugExample 14 BAB 3 Pelacakan Referensi Contoh Kode: TrackingReferenceContoh Contoh Kode: TemplateFunctionExample Managed Handle Contoh Kode: Ref TypeExample Ringkasan 17 v 7 vi Isi BAB 4 Kelas dan Objek Abstraksi Enkapsulasi Warisan Polimorfisme Manajemen Memori dalam Tipe NET Tipe Tidak Dirawat Sidang Campuran Ringkasan 23 BAB 5 Jenis Referensi Contoh Kode: Ref TypeExample Hapus dan Buang Selesai Contoh Kode: Finalisasi Contoh Stack Semantic Untuk Jenis Ref Referensi Nullptr T Itu adalah Ringkasan Penting 31 BAB 6 Jenis Nilai Contoh Kode: NilaiTipe Contoh Contoh Contoh: PassingValueTypesExample Summary 36 BAB 7 Objek yang Tidak Dikelola Contoh Kode: Ringkasan Ringkasan Contoh Tidak Nyata 39 BAB 8 Contoh Contoh Komposisi: Komposisi Contoh Contoh Kode: Tidak dikelola Contoh Contoh Contoh: ManagedCompositionExample Summary 48 BAB 9 Contoh Properti Kode: PropertiesExample Summary 50 BAB 10 Struktur dan Pencacahan Contoh Kode: ValueStructureExample Contoh Kode: ReferenceStructureExample Contoh Kode: EnumsExample Summary 53 8 Daftar Isi vii BAB 11 Inheritance Access Modifi ers Object Class Kelas Abstrak dan Sealed Contoh Kode: InheritanceExample Interfaces Contoh Kode: InterfaceExample Runtime Callable Ringkasan Wrapper 60 BAB 12 Konversi dan Pengecualian Mengubah Contoh Kode: ConvertExample Static Casting Contoh Kode: StaticCastExample Dynamic Casting Contoh Kode: DynamicCastExample Safe Casting Contoh Kode: Ringkasan SafeCastExample 65 BAB 13 Operator Overloading Contoh Kode: Ringkasan OpOverloadExample 69 BAB 14 Delegasi dan Agenda Delegasi Contoh Kode: Delegasi Contoh Contoh Contoh Multicasting: Contoh MulticastExample Contoh Kode: EventExample Wrappers Contoh Kode: WrapperExample Metode Asynchronous Panggilan Contoh Kode: Ringkasan AsynchEventExample 82 BAB 15 Array Contoh Kode: Contoh ManagedArrayExample Kode: PassingArraysExample Summary 85 vii 9 viii Daftar Isi BAB 16 Membangkitkan Bilangan Acak Contoh Kode: Contoh Contoh RandomExample: Ringkasan Ringkasan Sampel 89 BAB 17 Waktu dan Waktu Contoh Kode: Milliseconds Contoh Kode Contoh Stopwatch: StopwatchExample Timers Contoh Kode: FormsTimer Contoh Contoh Contoh: Kode Contoh ThreadingTimerExample: Ringkasan TimersTimerExample 98 BAB 18 Aliran Input dan Output FileStream Class Kelas StreamWriter Kelas File dan Direktori Kelas Aplikasi FileMode Enumeration Contoh Kode: StreamWriterExample Contoh Kode: StreamReaderExample Summary 101 BAB 19 Exception Handl Contoh Contoh: Pengecualian Contoh Catat Tipe C yang Tidak dikelola Ringkasan 105 BAB 20 Kumpulan Contoh Kode: HashtableExample Sorted List Class Contoh Kode: SortedListExample Thread Safety Generics Contoh Kode: LinkedListExample Contoh Kode: GenericsExample Summary 112 BAB 21 STLSTL Contoh Kode: STLExample Contoh Kode: Ringkasan STLExample 114 10 Daftar Isi ix BAB 22 Contoh DataSet Contoh: Ringkasan DataSetExample, DataRowCollections, dan Ringkasan DataReek 117 BAB 23 Menghubungkan ke Database Database Connection DataAdapter Contoh Kode: Contoh ADOContohkan Melalui Semua Data dalam DataSet Menggunakan Excel sebagai Sumber Data Menulis XML dari DataSet Memperbarui Database dengan Perubahan dalam Dataset Mengambil Data dengan Ringkasan DataReader 124 BAB 24 Bahasa Query Terstruktur Manipulasi Data Bahasa Memperbarui Database dengan Perubahan dalam Data Data Defi nisi Bahasa Ringkasan 140 BAB 25 XML Dokumen XML yang Terformat dengan Baik Dokumen XML yang Valid XML Schema Dokumen Parsers Contoh Kode: T Contoh Kode: XmlWriterContoh Contoh Contoh: XmlReaderExample Summary 146 BAB 26 Protokol Pertukaran Informasi Keuangan Protokol XML di Pasar Keuangan Ikhtisar Ringkasan FIX 151 BAB 27 Seriisasi Serialisasi Ringkasan Contoh 154 BAB 28 Panduan Windows Contoh Kode: Ringkasan WindowsServiceExample 159 11 x Daftar Isi BAB 29 Setup dan Paket Instalasi Contoh Kode: InstallationExample Summary 162 Bagian II: Concurrency BAB 30 Threading Threading Namespace Contoh Kode: ThreadExample Contoh Kode: ThreadAbortExample Thread Priority Contoh Kode: ThreadPriorityExample ThreadState Enumeration ThreadPool Class Contoh Kode: ThreadPoolExample Memperbarui Formulir dari Thread Lain Contoh Kode: FormUpdateExample Thread Safety Summary 175 BAB 31 Kelas Sinkronisasi Contoh Kode: Sinkronisasi Contoh Contoh Kelas Contoh Mutex: Contoh Kelas Semaphore Contoh Contoh: Contoh Kelas Contoh SemaphoreExample Monitor: Ringkasan Monitor 182 BAB 32 Socket Contoh Kode: Contoh Kode SynchronousServerContoh 189 Bagian III: Interoperabilitas dan Konektivitas BAB 33 Diagram Kelas Marsekal Marsekal: StringToCharArrayExample Summary 194 BAB 34 Pewarna Dalam dan Pinning Pointer Contoh Kode: InteriorPointerContoh Pinning Pointers Contoh Kode: PinningExample Summary 198 12 Daftar Isi xi BAB 35 Menghubungkan ke Dikelola Contoh DLL Contoh: Ringkasan DLLExample 201 BAB 36 Menghubungkan ke Component Object Model (COM) DLL dengan Kode Contoh COM Interop: Kode Contoh MyCOMLibrary: Menggunakan Ringkasan COMDLLExample 207 BAB 37 Menghubungkan ke C DLL dengan Layanan Pelatih Platform Memanggil Fungsi C-Gaya Contoh Kode: MyWin32Library Contoh Kode: MenggunakanWin32DLLExample Membuat Kode Contoh Objek: Kode Contoh MyWin32ClassLibrary: MenggunakanWin32ClassExample CallingConventionEnumeration Summary 216 BAB 38 Menghubungkan ke Excel Contoh Kode: Mengontrol Contoh Contoh Contoh: Ringkasan ExcelChartExample 221 BAB 39 Menghubungkan ke Trad ErAPI TraderAPI Overview FillObj InstrObjClass InstrNotifyClass OrderObj OrderProfi leclass OrderSetClass Contoh Kode: TraderAPIConnectionExample Summary 230 BAB 40 Menghubungkan ke XTAPI Contoh Kode: XTAPIConnectionExample Summary 233 13 xii Daftar Isi Bagian IV: Sistem Perdagangan Otomatis BAB 41 Membangun Sistem Perdagangan Beli vs. Membangun Pemetaan Data Kecepatan Perkembangan Sepuluh Hal yang Mempengaruhi Kecepatan Sistem Perdagangan Mendapatkan Kebenaran Logika Benar Sepuluh Hal yang Mempengaruhi Ketuntasan Sistem Perdagangan Ringkasan 245 BAB 42 Metodologi Pengembangan Sistem Perdagangan KV Perhitungan Dokumen dan Dokumen Uang Kembali Uji Implementasi Portofolio dan Ringkasan Risiko 257 BAB 43 Kelas Sistem Perdagangan Otomatis Kelas Kelas Order Order Order Bracket Tick Tick atau Bar Collection Bar System Manager Ringkasan Antarmuka Pengguna Grafis 265 BAB 44 Sistem Analisis Bingkai Single-Threaded, Technical Analysis Contoh: Ringkasan TechincalSystemExample 277 BAB 45 ProducerConsum Er Design Pattern Contoh Kode: Contoh Ringkasan ProducerConsumer 287 BAB 46 Sistem Arbitrase Multitelasis dan Statistik Contoh Contoh: Ringkasan Ringkasan Penyebaran Kesimpulan 14 Ucapan Terima Kasih Buku ini dimulai sebagai catatan kelas untuk kursus yang saya ajarkan di Institut Teknologi Illinois yang disebut Pemrograman Berorientasi Objek Lanjutan untuk Keuangan Pasar Di kelas ini kita membahas perancangan dan pengembangan sistem perdagangan otomatis menggunakan Microsoft Visual C. Ketika saya mulai mengajar kursus ini beberapa tahun yang lalu, saya tidak dapat menemukan buku yang mencakup semua topik yang diperlukan untuk membangun sistem perdagangan otomatis real-time dan sebagainya, Akibatnya, buku ini mencoba untuk melakukan hal itu sehingga menyatukan topik terkait pemrograman dan teknologi untuk pengembangan pemilihan perdagangan, perutean pesanan, manajemen pesanan, dan algoritma pengelolaan posisi. Saya berharap agar lebih banyak sekolah menawarkan kursus desain sistem perdagangan otomatis di masa depan dan buku ini akan sangat membantu dalam pengajaran mereka. Selanjutnya, buku ini adalah teks dasar untuk program Pengembang Sistem Bersertifikat Certified CTSD yang ditawarkan oleh Institute for Market Technology (i4mt. org). Ini adalah program sertifikasi baru yang terdiri dari tiga ujian, satu di bidang keuangan kuantitatif, satu strategi perdagangan sekuritas dan derivatif, dan satu dalam pemrograman ISO CC dan teknologi pasar. Program studi mandiri ini dirancang untuk mempertemukan ketrampilan-ketrampilan yang diminati di industri keuangan saat ini. Kandidat yang mencapai penunjukan CTSD akan menjadi orang berbakat. Seperti yang dapat kita bayangkan, tambahan kredit untuk menyelesaikan proyek ini harus diberikan kepada banyak teman, keluarga, dan rekan kerja: khususnya kepada istri saya, 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, dan semua rekan saya di IIT Center Untuk Pasar Keuangan Russell Wojcik, Dr. Michael Gorham, Keith Black, Dr. Michael Ong, Dr. John Bilson, Dr. Michael Kelly, dan Jodi Houlihan. Juga saya ingin mengucapkan terima kasih kepada banyak siswa yang telah mengikuti kursus saya dan telah memberikan umpan balik yang berharga. Tanpa bantuan mereka dan bantuan banyak orang lain, buku ini tidak akan pernah selesai. Xiii 15 xiv Ucapan Terima Kasih Buku ini ditulis untuk orang-orang yang memiliki pengetahuan tentang ISO C atau mungkin Java ,, atau COM. Bagi insinyur keuangan dan calon insinyur keuangan dengan latar belakang pemrograman umum, buku ini akan memberikan diskusi mendalam mengenai konsep pemrograman tingkat tinggi seperti penanganan event, interoperabilitas, konektivitas umpan data, dan konkurensi. Bagi pemrogram C yang berpengalaman, Anda mungkin menemukan bahwa buku ini memberikan pengenalan yang baik tentang penggunaan C dalam Kerangka Kerja. Apapun masalahnya, saya harap Anda belajar darinya dan terinspirasi untuk menggali lebih dalam topik pengembangan sistem perdagangan otomatis. Tolong berikan saya umpan balik yang Anda miliki. Saya berjanji untuk memperbarui situs web saya, secara teratur dengan koreksi errata dan contoh tambahan. 16 BAB 1 Pendahuluan Sistem perdagangan otomatis (atau algoritmik) terdiri dari banyak bagian, baik klien perangkat keras dan perangkat lunak, server, jaringan, database, mesin penghitung, antarmuka pemrograman aplikasi, umpan data real-time, dan antarmuka pengguna grafis. Namun, logika bisnis sistem perdagangan, yang terdiri dari algoritma seleksi perdagangan, manajemen pesanan, dan logika manajemen posisi, terdapat dalam perangkat lunak, dan buku ini berkaitan dengan enkapsulasi logika bisnis sistem perdagangan dalam perangkat lunak yang mengendalikan arus pasar. data. (Tidak ada nilai dalam buku ini.) Sistem perdagangan otomatis terdiri dari peraturan untuk masuk dan keluar dari posisi atau posisi dan teknologi, baik perangkat keras dan perangkat lunak, yang digunakan untuk mewujudkannya. Aturan ini adalah seperangkat operasi logis atau matematis yang dapat didasarkan pada penelitian kualitatif, teknis, atau kuantitatif. Jika kita ingin membangun sistem otomatis yang mengeksekusi perdagangan di bursa elektronik, kita perlu belajar bagaimana bekerja dengan data, data pasar real-time dan data historis, dalam kode. Lagipula, data adalah sumber kehidupan pasar elektronik, menurut David Norman dalam bukunya Professional Electronic Trading. Begitulah buku ini, menggunakan Visual C untuk mengelola data pasar keuangan (dan jumlahnya banyak) dalam aplikasi sistem perdagangan. Secara umum, buku ini mencakup tiga hal: 1. Mengelola data dalam memori. 2. Menyimpan data dan mengambil dari database. 3. Mengkomunikasikan data. Pemrograman kantor depan di pasar keuangan sebagian besar berkaitan dengan penghubung ke database, umpan data real-time, platform eksekusi pesanan, perpustakaan kuantum, mesin pengoptimalan, perangkat lunak charting, mesin pembuat laporan, teknologi warisan, dan Excel, hanya untuk beberapa nama saja. Agar berhasil mengelola data real-time dan historis, kita perlu memahami: 1. Arsitektur berbasis event. 2. Concurrency. 3. Konektivitas dan interoperabilitas. 1 17 2 BAB 1 Pendahuluan Sementara buku ini membahas lusinan isu teknologi penting yang akan Anda hadapi saat membangun sistem perdagangan otomatis di dunia nyata, ini tidak menunjukkan kepada Anda bagaimana membangun sistem perdagangan yang menguntungkan. (Penting untuk diketahui bahwa keunggulan teknologi dapat menjadi keunggulan kompetitif yang besar.) Ada empat disiplin ilmu yang masuk ke pengembangan sistem komputer trading otomatis, keuangan kuantitatif, strategi perdagangan, dan manajemen mutu dan ini adalah buku ilmu komputer. Pengembangan dan pengujian metode seleksi perdagangan dan pengelolaan risiko adalah topik untuk buku lainnya. Buku ini mencakup dasar-dasar apa yang harus diketahui insinyur keuangan tentang pemrograman di objek, SQL, multithreading, interoperabilitas, pesan, algoritma pemilihan pesanan, dan teknik manajemen pesanan. Dalam teks ini, saya telah mencoba memasukkan informasi yang berkaitan dengan pasar dan pekerjaan. Pengusaha saat ini di pasar keuangan menuntut kesiapan kerja. Jika Anda ingin mendapatkan pekerjaan di industri pengelolaan perdagangan dan uang, yang semakin hari semakin banyak didorong oleh sistem otomatis, Anda harus memiliki tingkat pengetahuan pemrograman yang kompetitif. Anda harus menyadari bahwa buku ini adalah ikhtisar. Itu tidak akan mengajarkan segalanya kepada anda. Teknologi sebagai topik jelas terlalu luas untuk dibahas dalam satu buku. Bahkan mempersempitnya ke VC karena pengembangan sistem perdagangan masih terlalu luas. Selama beberapa halaman, saya akan mempresentasikan beberapa gagasan penting, mencoba mengarahkan Anda ke arah yang benar, dan semoga pada akhirnya mengilhami Anda untuk melakukan penelitian tambahan mengenai topik pengembangan sistem perdagangan otomatis. Dari situlah, insinyur keuangan yang rajin harus menyelidiki lebih lanjut tentang ISO C-nya sendiri Buku ini mencakup aspek pemrograman pengembangan sistem perdagangan dan mengasumsikan bahwa Anda sudah familiar dengan konsep pemrograman ISO C, termasuk petunjuk, fungsi, objek, dan Template Standar Struktur Perpustakaan Buku Ini Sistem perdagangan otomatis menemukan bentuk paling murni dalam strategi frekuensi tinggi dimana kecepatan perhitungan dan eksekusi merupakan keunggulan kompetitif. Sistem lain, di mana milidetik tidak harus dari intinya, mungkin sepenuhnya otomatis atau sebagian otomatis. Teks ini akan berfokus pada mengenalkan konsep pemrograman dan desain untuk sistem frekuensi yang lebih tinggi. Pembahasan semua konsep teknologi alternatif perancangan sistem perdagangan dan penyajian sistem perdagangan yang lengkap berada di luar cakupan buku. Sistem perdagangan yang disajikan dalam buku ini secara drastis disederhanakan untuk menggambarkan konsep pemrograman dan desain yang umum. Buku ini terbagi menjadi empat bagian. Bagian pertama berfokus semata-mata pada pengenalan tipe dan teknik pemrograman Visual C. Bagian kedua berfokus pada multithreading. Yang ketiga berfokus pada interoperabilitas dan konektivitas dan yang keempat pada objek, pola desain, dan konsep arsitektur untuk pengembangan sistem perdagangan otomatis. Pada akhirnya, hanya membaca buku ini tidak akan membuat Anda ahli. Untuk benar-benar mempelajari materi dalam buku ini, Anda juga harus mengerjakan contoh kode yang disajikan. Hanya dengan melibatkan diri Anda dalam proses ini, dan selanjutnya melangkah melampaui itu, akankah Anda mendapatkan pemahaman dan intuisi. Ini kerja keras, tapi akan melunasi. BAGIAN I Pendahuluan untuk Visual C 2005 19 Halaman ini sengaja dikosongkan 20 BAB 2 Kerangka 2.1. MS Visual Studio 2005 Struktur Proyek Dalam MS Visual Studio 2005, aplikasi perangkat lunak Anda disebut solusi, dan solusi dapat dibuat dari satu atau lebih proyek, di mana setiap proyek berpotensi berada dalam bahasa Visual Studio yang berbeda. Selama buku ini, saya akan menyajikan solusi yang dikembangkan untuk sebagian besar di MS Visual C untuk dikelola atau aplikasi karena alasan yang akan segera saya jelaskan. Namun, Sadarilah bahwa Visual C bukan bahasa pemrograman baru, melainkan lingkungan pengembangan penuh yang memberikan dukungan yang meningkat untuk banyak jenis proyek C, termasuk: Proyek Perpustakaan Template Aktif (ATL). Proyek MS Foundation Classes (MFC). Atau konsol yang dikelola, proyek Windows atau DLL. Win32 Console memproyeksikan proyek ISO C. Proyek API Win32 dan DLL. Akibatnya, proyek Visual C untuk atau dikelola hanyalah salah satu dari beberapa bahasa C yang ditawarkan dalam Visual Studio 2005, dan ini adalah salah satu hal yang membedakan VC baru dari yang lain dalam keluarga yang pada dasarnya menyediakan lima bahasa C independen di dalamnya. Satu paket Jadi jika Anda ingin terus membuat aplikasi MFC, Anda bisa melakukannya seperti sebelumnya. Sebenarnya, dukungan untuk MFC dan ATL benar-benar telah diperbaiki di VS Pada versi Visual Studio sebelumnya, ekstensi ditambahkan ke namanya untuk membedakannya dari versi sebelumnya, seperti Visual Basic 6.0. Dengan munculnya VS 2005, ekstensi untuk nama biasanya tidak aktif dan kita dapat merujuk mereka sebagai VB, C, dan Visual C CCLI CCLI (Common Language Infrastructure) adalah turunan dari C. Menurut Stanley Lippman dari Microsoft: 5 21 6 BAB 2 Kerangka CLI mengacu pada Common Language Infrastructure, sebuah arsitektur multitier yang mendukung model pemrograman komponen dinamis. Dalam banyak hal, ini merupakan pembalikan lengkap dari model objek C. Lapisan perangkat lunak runtime, sistem eksekusi virtual, berjalan di antara program dan sistem operasi yang mendasarinya. Akses ke mesin yang mendasarinya terbilang terbatas. Akses ke jenis yang aktif dalam program pelaksana dan infrastruktur program terkait baik sebagai penemuan dan konstruksi didukung. Garis miring () mewakili ikatan antara C dan CLI Jadi, perkiraan pertama jawaban untuk apa CCLI adalah bahwa ini adalah pengikatan model objek C statis ke model objek komponen dinamis CLI. Singkatnya, ini adalah bagaimana Anda melakukan pemrograman menggunakan C daripada C atau Visual Basic. Seperti C dan CLI itu sendiri, CCLI sedang menjalani standardisasi di bawah European Computer Manufacturers Association (ECMA) dan akhirnya di bawah ISO. Runtime bahasa umum (CLR) adalah versi Microsoft dari CLI yang spesifik untuk sistem operasi Windows. Demikian pula Visual C adalah implementasi CCLI. Sebagai pendekatan kedua dari sebuah jawaban, CCLI mengintegrasikan model pemrograman dalam C dengan cara yang sama seperti, di Bell Laboratories, kami mengintegrasikan pemrograman generik menggunakan templat dalam C. yang ada saat itu. Dalam kedua kasus ini, investasi Anda dalam basis kode C yang ada Dan keahlian C yang ada dipelihara. Ini adalah persyaratan dasar yang penting untuk desain CCLI. Selama kursus buku ini, saya hanya akan mengacu pada implementasi Microsoft CCLI sebagai Visual C. Untuk artikel lengkap Lippman, kunjungi msdnmagissues0600purecdefault. aspx Mengapa Visual C Jadi mengapa Visual C Apa manfaat dari aplikasi yang dikelola atau C Cukup Menempatkan dan dalam kata-kata wakil presiden vendor perangkat lunak perdagangan utama di Chicago, NET adalah masa depan. Yang terpenting, Kerangka ini berisi banyak, banyak kelas yang membantu dalam pengembangan sistem perdagangan, seperti yang akan kita lihat. Selain itu, relatif terhadap bahasa lain, VC mengandung dukungan interoperabilitas yang jauh lebih besar antara kode yang dikelola dan tidak dikelola. Selain itu, di pasar keuangan, interoperabilitas adalah kunci. Di VC, kami memiliki kontrol yang tepat atas tumpukan tumpukan dan tumpukan yang dikelola, dan kode pengelolaan dan pengelolaan yang tidak dikelola dan semua dapat ada secara mulus dalam proyek yang sama. Ini memungkinkan kita untuk mengintegrasikan aplikasi, fungsi, dan objek C yang ada dengan cepat dan mudah ke dalam aplikasi baru. Hal ini terutama berlaku untuk aplikasi COM, yang banyak digunakan di industri keuangan dan tidak terkelola. Lebih jauh lagi, jika Anda memiliki perpustakaan objek atau fungsi keuangan yang ditulis dalam bahasa C asli, VC dengan dukungan interop yang dikelola terkelola secara keseluruhan akan memberi Anda kontrol yang luar biasa. Sebagai alternatif, jika Anda memiliki aplikasi C yang ingin Anda ubah, VC akan memberi Anda alat bahasa lain yang bisa dan tidak t. Akhirnya, sementara versi 2005 dari STL (dikenal sebagai STL) belum tersedia, akan segera dan mengubah kode STL-dependent asli akan sangat mudah. 22 2.6. KERANGKA The VC Compiler Berikut adalah beberapa hal yang perlu diingat tentang compiler VC. Kompiler VC, C1.exe, menggunakan ekstensi the. c untuk kompilasi C-only dan. cpp untuk C dan C. Juga, header standar tidak memerlukan ekstensi. h, karena Microsoft telah menyertakan versinya sendiri dari file-file ini di Ruang nama std Selanjutnya, jendela properti proyek menampilkan semua pengaturan kompilator untuk CC, termasuk linker dan membangun event. Kompilator Microsoft Cl. exe mengimplementasikan standar ANSI C dan ISO C dan memenuhi persyaratan 98 C menurut Microsoft. Compiler menawarkan Solution Configurations for Debug builds dan Release builds. Dengan membangun Debug, kita bisa berinteraksi dengan kode kita selama runtime. Ini sangat membantu. Namun, tidak ada pengoptimalan yang dilakukan dan untuk itu kami menggunakan Release build, yang akan menghasilkan kode yang lebih cepat dan optimal. Kompilator memungkinkan kita menggabungkan kode C asli dalam proyek kita dan mengkompilasi terlebih dahulu menjadi Microsoft Intermediate Language (MSIL). Kemudian MSIL diubah menjadi kode asli oleh compiler Just In Time (JIT). Dengan JIT beberapa operasi akan lebih cepat dari C asli, sedangkan yang lain akan lebih lambat. Akibatnya, ada trade-off antara kecepatan pengembangan dan kecepatan eksekusi. Namun, ada beberapa hal yang bisa kita lakukan untuk meminimalkan biaya operasi tertentu. Kompiler VC dan JIT dapat disetel untuk menghasilkan kode tercepat dengan menggunakan opsi kompiler yang tersedia. Jika Anda serius tentang kecepatan, luangkan waktu untuk menyelidiki kompiler VC Microsoft lebih lanjut. Bagaimana dengan Speed ​​Speed ​​yang penting, tentu saja. Untuk diskusi mendalam tentang pertimbangan kecepatan dalam kode yang dikelola, saya akan mengarahkan Anda ke beberapa artikel unggulan di Perpustakaan MSDN (msdn. microsoft. com comlibrary): A Baker s Dozen: Tiga Belas Hal yang Harus Anda Ketahui Sebelum Memasuki Program Visual C Anda Untuk Visual Studio 2005 oleh Stanley Lippman. Praktik Terbaik untuk Menulis Kode yang Efisien dan Terpercaya dengan CCLI oleh Kenny Kerr. C: Bahasa yang Paling Kuat untuk Kerangka Pemrograman oleh Kenny Kerr. Menulis Kode Dikeluarkan Cepat: Ketahui Apa yang Dibutuhkan oleh Jan Gray. Menulis Aplikasi dengan Kinerja Tinggi: Primer oleh Gregor Noriskin (mencakup ikhtisar profiler CLR). Tip untuk Memperbaiki Kode Waktu-Kritis. Praktik Terbaik Pengoptimalan di bagian Visual C Kerangka Saat membuat aplikasi Visual C yang dikelola, program kami dikembangkan, disusun, dan dijalankan dalam Kerangka. Kerangka terdiri dari tiga bagian: 23 8 BAB 2 Kerangka 1. Common Language Runtime (CLR). 2. Perpustakaan Kelas. 3. ASP. ASP adalah platform pengembangan web Microsoft untuk membangun aplikasi web enterprise, yang berjalan terlalu lambat untuk real-time, aplikasi pasar keuangan, jadi kami tidak akan meluangkan waktu untuk memeriksanya. Sebaliknya, kita akan menghabiskan waktu kita untuk belajar tentang runtime bahasa umum dan perpustakaan kelas dan bagaimana kita dapat menggunakannya untuk membangun aplikasi keuangan yang berpotensi berjalan di beberapa sistem operasi, tidak hanya Windows, termasuk Unix, Linux, dan Mac Common Language Runtime The CLR menggerakkan eksekusi kode dalam Kerangka dan menyediakan program berbasis integrasi lintas bahasa, keamanan, pengelolaan memori dinamis, dan layanan debugging. Selanjutnya, CLR mengendalikan kode yang kami sebut managed code, yang dieksekusi di dalam tumpukan yang dikelola. Artinya, tumpukan yang dikelola dikendalikan oleh Kerangka Kerja daripada sistem operasi. Kode yang tidak dikelola (atau tidak kode), bagaimanapun, dikendalikan oleh sistem operasi. CLR juga menyediakan pengelolaan memori dinamis dengan menggunakan pengumpul sampah untuk mengelola alokasi dan deallokasi ruang memori, menghilangkan masalah kebocoran memori umum yang sering terjadi pada perangkat lunak. Alokasi memori CLR pada tumpukan yang dikelola adalah, ternyata, sebenarnya lebih cepat daripada alokasi tumpukan yang tidak terkelola dan hampir secepat alokasi memori stack karena mengalokasikan lokasi memori bersebelahan dengan hanya menambahkan pointer. Dalam, compiler mengkompilasi kode sumber yang dikelola terlebih dahulu ke dalam MSIL. Sebelum kode dijalankan, MSIL diubah oleh compiler just-in-time (JIT) yang spesifik untuk arsitektur komputer Anda. JIT mengubah MSIL menjadi bahasa mesin, atau kode asli, saat pengumpulan sampah Sampah Pengumpul sampah menentukan waktu terbaik untuk melakukan pengumpulan objek yang tidak diferensikan. Pengumpul sampah melepaskan ruang memori yang dialokasikan ke objek yang tidak lagi direferensikan (atau, ditunjukkan) di dalam aplikasi. Kerangka ini menyimpan daftar referensi aktif yang digunakan compiler JIT dan CLR. Pengumpul sampah menggunakan daftar ini untuk memeriksa semua referensi aplikasi. Objek yang tidak masuk dalam daftar dianggap tidak terjangkau dan ruang memori akan dilepaskan. Akibatnya, pengumpul sampah memeriksa tumpukan yang dikelola dan menemukan blok-blok ruang yang ditempati oleh benda-benda yang tidak diferensikan. Pada saat yang sama, lokasi memori yang direferensikan dipadatkan dan dipindahkan dan pembaruan yang diperlukan pada referensi pointer dibuat. Penting untuk dicatat bahwa pengumpul sampah akan memindahkan benda-benda di sekitar ingatan tanpa sepengetahuan kita. Hal ini memiliki implikasi penting pada Assemblies Assemblies yang membentuk blok bangunan fundamental untuk Kerangka dan setiap aplikasi yang dikembangkan di dalamnya. Sidang paling sering ada sebagai file executable atau file library dynamic link dan berisi kelompok kelas yang membentuk unit fungsional logis. 24 2.7. CONTOH KODE: MESSAGEBOXEXAMPLE 9 Assemblies berisi informasi tentang konten, versi, dan dependensi sebagai akibat aplikasi yang kita buat dengan Visual C tidak perlu bergantung pada nilai registri agar bekerja dengan baik. Karena registri tidak diperlukan, biasanya kita dapat menginstal aplikasi Visual C hanya dengan menyalin direktori yang dapat dieksekusi ke komputer target. Namespaces Namespace mengatur ribuan kelas di perpustakaan, mencegah kerancuan, dan menyederhanakan referensi, seperti yang akan kita lihat. (Program VC yang kita tulis akan sering mengandung atau menggunakan beberapa ruang nama). Dalam namespace Sistem adalah namespace root dan berisi tipe data primitif dan kelas dasar seperti Object (dari mana semua objek diturunkan), String, Exception, dan the garbage Kelas kolektor, GC Dokumentasi Visual Studio (File Bantuan) berisi halaman Referensi Perpustakaan Kerangka Kerja yang menyediakan daftar lengkap ruang nama dengan deskripsi. Karena semua pemrograman bergantung pada objek yang ada di ruang nama ini, Anda mungkin ingin meluangkan waktu untuk mengenal dengan baik ruang kelas yang berbeda dan jenis objek yang berisi Nama Penuh Penuh Saat menggunakan perpustakaan, kita dapat memberi instantiate objek yang didefinisikan di lokasi eksternal, seperti Selama kita menambahkan referensi ke majelis dan kemudian gunakan nama yang memenuhi syarat untuk kelas dalam kode kita. Nama yang memenuhi syarat adalah referensi kelas yang diawali dengan nama namespace-nya. 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. Click 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. Tapi Itu Dengan Strategi Perdagangan Algoritma Kita Sepertinya tidak mungkin. Salah satu sistem perdagangan algoritmik dengan begitu banyak identifikasi tren, analisis siklus, aliran volume sisi buquell, strategi perdagangan ganda, entry dinamis, harga target dan stop, dan teknologi sinyal ultra cepat. Tapi memang begitu. Sebenarnya, platform sistem perdagangan algoritma AlgoTrades adalah satu-satunya dari jenisnya. Tidak ada lagi pencarian untuk saham panas, sektor, komoditas, indeks, atau opini pasar membaca. Algotrades melakukan semua pencarian, timing dan trading untuk Anda dengan menggunakan sistem perdagangan algoritmik. Strategi yang terbukti AlgoTrades dapat diikuti secara manual dengan menerima email dan alert teks SMS, atau bisa jadi 100 perdagangan bebas tangan, terserah Anda Anda dapat mengaktifkan perdagangan otomatis onoff kapan saja sehingga Anda selalu mengendalikan takdir Anda. Sistem Perdagangan Otomatis untuk Investor yang Cerdas Copyright 2017 - ALGOTRADES - Sistem Perdagangan Algoritma Otomatis ATURAN CFTC 4.41 - HASIL KINERJA HIPOTHETIK ATAU SIMULASI MEMILIKI BATASAN TERTENTU. MELIHAT KINERJA KINERJA SEBENARNYA, HASIL YANG SIMULASI JANGAN MENYATAKAN PERDAGANGAN YANG BENAR. JUGA, SEJAK TRADES BELUM DIPERLUKAN, HASIL YANG DAPAT MEMILIKI BAWAH ATAU BAHAN YANG DIPERLUKAN UNTUK DAMPAKNYA, JIKA ADA, FAKTOR PASAR TERTENTU, SEPERTI KURANGNYA LIKUIDITAS. PROGRAM PERDAGANGAN SIMULASI DALAM UMUM JUGA TERTARIK FAKTA BAHWA MEREKA DITANDATANGANI DENGAN MANFAAT HINDSIGHT. TIDAK ADA REPRESENTASI YANG DIBUAT BAHWA SETIAP AKUN AKAN ATAU CUKUP UNTUK MENCAPAI KEUNTUNGAN ATAU KERUGIAN YANG SESUAI DENGAN MEREKA YANG DIMILIKI. Tidak ada representasi yang dibuat atau tersirat bahwa penggunaan sistem perdagangan algoritmik akan menghasilkan pendapatan atau menjamin keuntungan. Ada risiko kerugian yang besar terkait dengan perdagangan berjangka dan dana perdagangan yang diperdagangkan. Perdagangan berjangka dan pertukaran perdagangan yang diperdagangkan melibatkan risiko kerugian yang besar dan tidak sesuai untuk semua orang. Hasil ini didasarkan pada hasil kinerja simulasi atau hipotetis yang memiliki keterbatasan inheren tertentu. Tidak seperti hasil yang ditunjukkan dalam catatan kinerja aktual, hasil ini tidak mewakili perdagangan aktual. Juga, karena perdagangan ini belum benar-benar dijalankan, hasil ini mungkin kurang atau terlalu diimbangi dampaknya, jika ada, faktor pasar tertentu, seperti kurangnya likuiditas. Simulasi atau hipotetis program perdagangan pada umumnya juga tunduk pada kenyataan bahwa mereka dirancang dengan manfaat dari belakang. Tidak ada perwakilan yang dibuat bahwa setiap akun akan atau mungkin akan mencapai keuntungan atau kerugian yang serupa dengan yang ditunjukkan. Informasi di situs ini telah disiapkan tanpa memperhatikan tujuan investasi, situasi keuangan dan kebutuhan investor tertentu dan selanjutnya menyarankan pelanggan untuk tidak melakukan tindakan apapun tanpa mendapatkan saran khusus dari penasihat keuangan mereka untuk tidak mengandalkan informasi dari situs web sebagai dasar utama. Untuk keputusan investasi mereka dan untuk mempertimbangkan profil risiko mereka sendiri, toleransi risiko, dan stop loss mereka sendiri. - 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. Hal. 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. Click 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.

No comments:

Post a Comment