Friday 14 April 2017

Java Trading System Architektur

W e l c o m e Willkommen im Home of the Open Java Trading System Das Open Java Trading System (OJTS) soll eine gemeinsame Infrastruktur sein, um Aktienhandelssysteme zu entwickeln. Es besteht aus vier Teilen: dem Sammeln von Rohdaten über das Internet die Erkennung von Handelssignalen ein Visualisierungsmodul und Module zur Verbindung mit den programmatischen Schnittstellen von Handelsplattformen wie Banken. Ziel der Projekte ist es, eine selbstständige, reine Java (plattformunabhängige) gemeinsame Infrastruktur für Entwickler von Handelssystemen zur Verfügung zu stellen. Einige der Aspekte, die angesprochen werden sollten, sind die Bereitstellung eines gemeinsamen SQL92-kompatiblen Datenbankschemas für die Speicherung von Finanzdaten, gemeinsame Java-Schnittstellen für den Austausch von Daten zwischen verschiedenen Modulen, die Visualisierung von Roh-Finanzdaten und Trading-Signale und mehrere andere gemeinsame Aspekte, die benötigt werden, um zu erstellen Ein endgültiges Handelssystem. Wegen meiner Arbeit und Familie finde ich nicht die Zeit, OJTS länger zu verbessern. Ich bin weiterhin die Aktualisierung der Links Abschnitt unten, die Sie zu mehr aktive Java Open-Source-Projekte in diesem Bereich führen wird, obwohl. In der Tat als Folge meines Interesses an der Dynamik der Aktienmärkte begann ich eine Reise in die tieferen Details der Volkswirtschaft, um Wechselkurse zu verstehen. Dieses Thema führt mich schließlich zu einem tieferen Studium des Geldes in sich selbst als die metrische Einheit, die wir in der Wirtschaft verwenden, um Wert, Erfolg oder Nutzen zu messen. Dieses Thema erwies sich als äußerst interessant, aber gleichzeitig war es sehr schwer, irgendwelche Informationen darüber zu finden, wie unser Geldsystem funktioniert. Gehen Sie herum und fragen Sie Leute, wo Geld kommt, wer es schafft und was seinen Wert bestimmt. Sie werden feststellen, dass auch die Leute, die einen Master-Abschluss oder Phd haben. In der Wirtschaft wird diese Details nicht kennen. Oh, ja, sie werden in einigen kryptischen Fachbegriffen antworten, aber sie werden nicht in der Lage sein, ein einfaches Diagramm zu zeichnen, das den Prozess umreißt. H. G. Wells soll berichtet haben: Um die Währung zu schreiben, gilt allgemein als eine anstößige, ja fast unanständige Praxis. Die Redakteure werden den Schriftsteller fast tränenreich anflehen, nicht über Geld zu schreiben, nicht weil es ein uninteressantes Thema ist, sondern weil es immer ein zutiefst beunruhigender war. Ich schlage vor jeder Person, die in einer demokratischen Gesellschaft lebt, um über dieses Thema zu lesen. Es beeinflusst unser Leben jeden Tag in einem Ausmaß, das nicht übertrieben werden kann. Meiner Meinung nach sollte jeder Bürger eines demokratischen Landes auf dieser Welt wissen, woher unser Geld kommt. Wahrscheinlich bist du auf diese Website gekommen, um nach Werkzeugen zu suchen, die dir helfen, deinen Geldvermögen zu erhöhen. Um zu verstehen, die metrische Einheit Geld (egal ob Dollar oder Euro) wird ein wichtiger Bestandteil in Ihrem Toolkit für Geld zu verdienen. Wenn Sie wenig Zeit haben und sich nur leisten können, ein einziges Buch über dieses Thema zu lesen, dann schlage ich vor, dass Sie Reichtum, virtuellen Reichtum und Schulden von Frederick Soddy lesen. Ich konnte eine gebrauchte Kopie über Amazon für 23.48 kaufen, aber es gibt auch eine Online-Version. Du brauchst das DjVu Plugin, um es zu lesen. Dieses Buch wurde ursprünglich 1929 veröffentlicht, beschreibt aber die eigentlichen Tatsachen sehr gut. Auch wenn ich nicht mit allen Schlussfolgerungen von Frederick Soddy einverstanden bin, ist seine Arbeit angenehm gedacht und wird Sie dazu bringen, die richtigen Fragen zu stellen. N e w s Releases, Bugfixes und aktualisierte Dokumentation Angekündigt die Aussetzung der aktiven Entwicklung und hinzugefügt Verweise auf Informationen über unsere monetären Systeme (DollarEuro). Hinzugefügt Links zu anderen interessanten Java-Trading-System-Projekte. Ich untersuche, wie man OJTS kompatibler zu anderen Java-Handelssystem Bemühungen machen kann. Investitions - und Handelssystem-Dokumentationsprojekt finden Sie unter ITSdoc. org. Es gibt ein neues Wiki bei ITSdoc. org, das sich auf die Verteilung von Wissen im Bereich der Investitions - und Handelssysteme konzentriert. Die Idee hinter ITSdoc. org ist, eine Kooperationsplattform ähnlich wie wikipedia zu haben, die der Gemeinschaft hilft, Wissen zu teilen. OpenJavaTradingSystem v0.13 veröffentlicht. Gestern habe ich die Version 0.13 der OpenJavaTradingSystem Bibliothek veröffentlicht. Zu den neuen Features gehören: Datenabruf für Aktien, Fonds und Währungen von OnVista. Umsetzung von Währungsumrechnungen und Umbauten. Portfolios sind implementiert und Sie können mit Portfolios genauso arbeiten wie bei einzelnen Sicherheitspapieren. Ein allgemeiner Rahmen für die Anwendung von Algorithmen auf Börsen-Zeitreihen hinzugefügt. Umschalten von der interaktiven SISCScheme-Shell auf ABCLCommonLisp und dessen Editor mit dem Namen J. Hinzugefügt wurde ein allgemeiner Daten-Caching-Mechanismus zum Zwischenspeichern von Daten, die bereits über das Internet im Dateisystem abgerufen wurden. Plus viele weitere kleinere Verbesserungen Wenn Sie sich für diese neue Version interessieren, sollten Sie am Quickstartscreenshot-Bereich starten. Das Handbuch ist noch nicht aktualisiert, aber es kann Ihnen trotzdem einige wertvolle Hintergrundinformationen geben, wenn Sie die Bibliothek in Ihrem Projekt nutzen möchten. Die Dokumentation sollte bald aktualisiert werden. Zurzeit gibt es nicht viel Entwicklung, denn ich aktualisiere mein Wissen über bayesische Netzwerke. Siehe zB die Liste der Bücher auf meiner Website. Zwei sehr interessante Projekte in dieser Hinsicht sind WEKA und BNJ. Bald werde ich die Entwicklung fortsetzen und ich werde damit beginnen, die erste Intelligenz in das System zu integrieren. Heute stelle ich die erste Version in den Aktenbereich des Sourceforge Downloadbereichs. Außerdem habe ich das Handbuch aktualisiert, um die interaktive Nutzung des Projekts über die SISC-Scheme-Schicht zu dokumentieren. Für die ungeduldigen hier ist ein quickstartscreenshot Abschnitt, um dich zu gehen. D o c u m e n t a t i o n Dokumente, die die Einbauten des Projekts beschreiben. Java Datenobjekte und Schnittstellendokumentation gtgtHTML gtgtPDF Anwendungsdokumentation gtgtHTML gtgtPDF Investitions - und Handelssystem Dokumentation Projekt gtgtITSdoc. org T echnologie Drittanbieter-Bausteine ​​in diesem Projekt verwendet HSQL Datenbank-Engine (Lizenz: hsqldblic. txt) Die HSQLDB ist die Datenbank-Engine, die mit dem Projekt, damit Sie sofort mit dem OJTS beginnen können, ohne eine Drittanbieter-Datenbank zu installieren. Aber wenn Sie planen, eine andere SQL92-kompatible Datenbank zu verwenden, dann ist dies eine Konfigurationsoption. Castor (Lizenz: Die Exolab Lizenz) Castor ist ein Open Source Datenbindungsrahmen für Javatm. Es ist der kürzeste Weg zwischen Java-Objekten, XML-Dokumenten und relationalen Tabellen. Castor bietet Java-to-XML-Bindung, Java-to-SQL-Persistenz und vieles mehr. Castor Doclet (Lizenz: GNU LGPL v2.1) Java-Doclet, um sowohl Mapping - als auch DDL-Dateien für Castor JDO und Castor XML zu generieren. TestMaker (Lizenz: TestMaker Open-Source-Lizenz) Aus dem TestMaker-Projekt wird nur die Implementierung der Protokolle wie HTTP oder HTTPS zum Sammeln von Daten aus dem Web verwendet. JCookie (Lizenz: GNU LGPL v2.1) Die jCookie Bibliothek ist notwendig, damit die TestMaker Bibliotheken funktionieren. Htmlparser (Lizenz: GNU LGPL v2.1) Die htmlparser-Bibliothek wird verwendet, um die Daten aus Web-Ressourcen zu extrahieren. ABCLCommonLisp (Lizenz: GNU GPL v2) ABCL (Armed Bear Common Lisp) wird verwendet, um das algorithmische Herz des Projekts in der Programmiersprache ANSI Common Lisp zu implementieren. JFreeChart (Lizenz: GNU LGPL v2.1) JFreeChart dient der Visualisierung von Finanzdaten als Charts. JSci (Lizenz: GNU LGPL v2.1) JSci - Eine wissenschaftliche API für Java. Joda Time (Lizenz: Home Grown OpenSource Lizenz) Joda Time ersetzt die ursprünglichen JDK Date und Time Klassen. L i n k s Links zu anderen Projekten Die JavaTraders Google Gruppe ist vielleicht der beste Eintrag für Sie, um sich über andere Java basierte Handelssysteme und Tools zu informieren. L icense Nutzungsbedingungen Der Code des Projekts ist unter den Bedingungen der LGPL lizenziert und alle Unterlagen, die Sie in diesem Projekt finden, sind unter den Bedingungen der FDL. A lizenziert. Intraday Trading System Diese Webseiten kommen aus einer Arbeit Ich habe auf einem Intra-Day-Trading-System, implementiert in Java. Diese Software läuft unter dem Tomcat Java Applikationsserver und unterstützt Trading-Modelle, die einen Echtzeit-Marktdatenstrom lesen. Auf Basis dieses Datenstroms generiert die Software Kauf - und Verkaufsaufträge und verfolgt ihre Marktposition. Bitte schicken Sie mir keine E-Mail, um zu fragen, welche Handelstechniken Sie reich machen werden. Ich weiß viel über die Implementierung komplexer Software-Systeme und ich weiß etwas über den Aufbau von Markt-Handelssystemen. Ich arbeite aber immer noch für ein Leben, so dass es scheint, dass ich die geheime Sauce selbst nicht entdeckt habe. Ich habe keinen bemerkenswerten Markt juju, um Ihnen zu vermitteln. Unter bestimmten Voraussetzungen werde ich externe Beratungsprojekte betrachten. Ein Beratungsprojekt muss von meinem Arbeitgeber genehmigt werden, also gibt es einen Aufwand beim Einstieg (das letzte Mal habe ich eines dieser Projekte gemacht, es dauerte einen Monat, um genehmigt zu werden). Ich kann nur mit US-Bürgern arbeiten, Bürger des britischen Commonwealth oder NATO-Verbündeten. Die erste Regel für diejenigen, die für stündliche Preise arbeiten, ist bezahlt zu werden, also bitte schreiben Sie mir nicht, was darauf hindeutet, dass ich kostenlos für einen Anteil an Ihrem Venture arbeite. Ich bin ein sehr erfahrener Software-Ingenieur und Informatiker und meine Stundengebühren spiegeln dies. Tradeengine. tar. gz Dies ist das Handelssystem, das ich entwickelt habe. Ich besitze das Urheberrecht für diese Software und darf es nicht für irgendwelche kommerziellen Zwecke ohne Erlaubnis verwenden. Auch dürfen Sie diese Software nicht ohne Erlaubnis für jede Art von Markthandel verwenden. Da Sie nicht berechtigt sind, diese Software für irgendetwas anderes als Referenz zu verwenden, können Sie mich nicht für irgendeinen Fehler in dieser Software oder Probleme, die bei der Verwendung auftreten, haftbar machen. Diese Software wird ein bisschen veraltet. Es gibt noch viele weitere Java-Ressourcen. Obwohl dies die Kernarchitektur zeigt, könnte ein viel besseres System mit aktuellen Java-Ressourcen implementiert werden. Das Handelssystem ist so konzipiert, dass es mit dem Interactive Brokers Handelssystem über die Java-Schnittstelle arbeitet. Diese Webseiten bestehen aus Notizen über die Gestaltung des Handelssystems, das ich entwickelt habe. Es gibt auch Notizen zu den Experimenten mit einigen technischen Analyse-Stil intra-Tage-Handelsmodelle. Ein Java-Handelssystem wird durch eine komplexe Software-Infrastruktur unterstützt. Dazu gehören der Apache Tomcat Webserver (Application Sever), Echtzeit-Daten-Feeds und Software zur Unterstützung der Webbrowser-basierten Interaktion mit dem Benutzer. Bei der Erforschung der Software, dass ich das Handelssystem unterstützen müsste, habe ich diese Notizen erstellt. Ian Kaplan Januar 2009 Letzte Aktualisierung: November 2011Best Programmiersprache für algorithmische Handelssysteme Eine der häufigsten Fragen, die ich im QS-Postfach bekomme, ist Was ist die beste Programmiersprache für den algorithmischen Handel. Die kurze Antwort ist, dass es keine beste Sprache gibt. Strategieparameter, Leistung, Modularität, Entwicklung, Ausfallsicherheit und Kosten sind zu berücksichtigen. Dieser Artikel skizziert die notwendigen Komponenten einer algorithmischen Handelssystemarchitektur und wie Entscheidungen in Bezug auf die Umsetzung die Wahl der Sprache beeinflussen. Erstens werden die Hauptkomponenten eines algorithmischen Handelssystems betrachtet, wie die Forschungsinstrumente, Portfolio-Optimierer, Risikomanager und Ausführungs-Engine. Anschließend werden verschiedene Handelsstrategien untersucht und wie sie das Design des Systems beeinflussen. Insbesondere wird die Häufigkeit des Handels und des wahrscheinlichen Handelsvolumens diskutiert. Sobald die Handelsstrategie ausgewählt wurde, ist es notwendig, das gesamte System zu architektieren. Dazu gehören die Auswahl der Hardware, das Betriebssystem und die System-Resilienz gegen seltene, potenziell katastrophale Ereignisse. Während die Architektur berücksichtigt wird, muss die Leistung - sowohl an die Forschungsinstrumente als auch an die Live-Ausführungsumgebung - gebührend berücksichtigt werden. Was ist das Trading-System zu tun Vor der Entscheidung über die beste Sprache, mit denen ein automatisiertes Handelssystem zu schreiben ist es notwendig, die Anforderungen zu definieren. Wird das System rein ausgeführt sein, wird das System ein Risikomanagement - oder Portfolio-Konstruktionsmodul erfordern. Das System benötigt einen leistungsstarken Backtester. Für die meisten Strategien kann das Handelssystem in zwei Kategorien aufgeteilt werden: Forschung und Signalgenerierung. Die Forschung beschäftigt sich mit der Bewertung einer Strategieleistung über historische Daten. Der Prozess der Auswertung einer Handelsstrategie gegenüber früheren Marktdaten wird als Backtesting bezeichnet. Die Datengröße und die algorithmische Komplexität haben einen großen Einfluss auf die Rechenintensität des Backtests. CPU-Geschwindigkeit und Parallelität sind oft die begrenzenden Faktoren bei der Optimierung der Forschungsdurchführungsgeschwindigkeit. Die Signalgenerierung beschäftigt sich mit der Erzeugung eines Satzes von Handelssignalen aus einem Algorithmus und dem Versenden solcher Aufträge auf den Markt, in der Regel über eine Vermittlung. Für bestimmte Strategien ist ein hohes Leistungsniveau erforderlich. IO-Themen wie Netzwerkbandbreite und Latenz sind oft der begrenzende Faktor bei der Optimierung von Ausführungssystemen. So kann die Wahl der Sprachen für jede Komponente Ihres Gesamtsystems ganz anders sein. Typ, Häufigkeit und Volumen der Strategie Die Art der eingesetzten algorithmischen Strategie wird sich erheblich auf die Gestaltung des Systems auswirken. Es wird notwendig sein, die gehandelten Märkte, die Konnektivität zu externen Datenanbietern, die Häufigkeit und das Volumen der Strategie, den Kompromiss zwischen der Leichtigkeit der Entwicklung und der Leistungsoptimierung sowie jede kundenspezifische Hardware, einschließlich der zusammengesetzten Sitte, zu berücksichtigen Server, GPUs oder FPGAs, die notwendig sein könnten. Die Technologie-Entscheidungen für eine niederfrequente US-Aktienstrategie unterscheiden sich deutlich von denen eines hochfrequenten statistischen Arbitrage-Strategiehandels auf dem Futures-Markt. Vor der Wahl der Sprache müssen viele Datenverkäufer ausgewertet werden, die sich auf die jeweilige Strategie beziehen. Es wird notwendig sein, die Konnektivität mit dem Anbieter, die Struktur von APIs, die Aktualität der Daten, die Speicheranforderungen und die Widerstandsfähigkeit im Angesicht eines Verkäufers, der offline geht, zu betrachten. Es ist auch klug, schnellen Zugriff auf mehrere Anbieter zu besitzen. Verschiedene Instrumente haben alle ihre eigenen Speicherquirks, Beispiele dafür sind mehrere Tickersymbole für Aktien und Verfallsdaten für Futures (ganz zu schweigen von bestimmten OTC-Daten). Dies muss in das Plattformdesign berücksichtigt werden. Häufigkeit der Strategie ist wahrscheinlich einer der größten Treiber, wie der Technologie-Stack definiert werden wird. Strategien, die Daten häufiger einsetzen als kleinere oder zweitens Bars, bedürfen einer beträchtlichen Berücksichtigung der Leistung. Eine Strategie, die zweitens Stäbe übersteigt (d. h. Tick-Daten), führt zu einem leistungsgesteuerten Design als primäre Anforderung. Für Hochfrequenzstrategien müssen erhebliche Marktdaten gespeichert und ausgewertet werden. Software wie HDF5 oder kdb werden häufig für diese Rollen verwendet. Um die umfangreichen Datenmengen für HFT-Anwendungen zu verarbeiten, muss ein weitgehend optimiertes Backtester - und Ausführungssystem eingesetzt werden. CC (möglicherweise mit einigen Assembler) ist wahrscheinlich der stärkste Sprachkandidat. Ultra-High-Frequenz-Strategien werden fast sicherlich benutzerdefinierte Hardware wie FPGAs, Austausch Co-Location und Kern-Netzwerk-Interface-Tuning. Forschungssysteme Forschungssysteme beinhalten in der Regel eine Mischung aus interaktiver Entwicklung und automatisiertem Scripting. Die ehemalige findet oft in einer IDE wie Visual Studio, MatLab oder R Studio statt. Letzteres beinhaltet umfangreiche numerische Berechnungen über zahlreiche Parameter und Datenpunkte. Dies führt zu einer Sprachwahl, die eine einfache Umgebung bietet, um Code zu testen, aber auch eine ausreichende Leistung zur Bewertung von Strategien über mehrere Parameter-Dimensionen. Typische IDEs in diesem Bereich sind Microsoft Visual CC, das umfangreiche Debugging-Dienstprogramme, Code-Completion-Funktionen (via Intellisense) und einfache Übersichten des gesamten Projektstacks (über die Datenbank ORM, LINQ) MatLab enthält. Die für umfangreiche numerische lineare Algebra und vektorisierte Operationen ausgelegt ist, aber in einer interaktiven Konsolenweise R Studio. Die die R statistische Sprachkonsole in einer vollwertigen IDE Eclipse IDE für Linux Java und C und semi-proprietäre IDEs wie Enthought Canopy für Python, die Datenanalyse Bibliotheken wie NumPy enthalten. SciPy Scikit-lernen und pandas in einer einzigen interaktiven (Konsole) Umgebung. Für das numerische Backtesting sind alle oben genannten Sprachen geeignet, obwohl es nicht notwendig ist, eine GUIIDE zu verwenden, da der Code im Hintergrund ausgeführt wird. Die Hauptbetrachtung in diesem Stadium ist die der Ausführungsgeschwindigkeit. Eine kompilierte Sprache (wie z. B. C) ist oft nützlich, wenn die Backtesting-Parameter-Dimensionen groß sind. Denken Sie daran, dass es notwendig ist, vor solchen Systemen vorsichtig zu sein, wenn dies der Fall ist. Interpretierte Sprachen wie Python nutzen oft Hochleistungsbibliotheken wie NumPypandas für den Backtesting-Schritt, um ein angemessenes Maß an Wettbewerbsfähigkeit mit kompilierten Äquivalenten aufrechtzuerhalten. Letztlich wird die für das Backtesting gewählte Sprache durch spezifische algorithmische Bedürfnisse sowie die Bandbreite der in der Sprache verfügbaren Bibliotheken bestimmt (mehr dazu unten). Allerdings kann die Sprache, die für den Backtester und die Forschungsumgebungen verwendet wird, völlig unabhängig von denen sein, die in der Portfolio-Konstruktion, dem Risikomanagement und den Ausführungskomponenten verwendet werden, wie zu sehen ist. Portfolio-Konstruktion und Risikomanagement Die Portfoliokonstruktions - und Risikomanagementkomponenten werden oft von den algorithmischen Händlern des Einzelhandels übersehen. Das ist fast immer ein Fehler. Diese Werkzeuge bieten den Mechanismus, durch den das Kapital erhalten bleibt. Sie versuchen nicht nur, die Anzahl der riskanten Wetten zu lindern, sondern auch die Churn der Trades selbst zu minimieren und die Transaktionskosten zu senken. Ausgefeilte Versionen dieser Komponenten können sich erheblich auf die Qualität und die Konsequenz der Rentabilität auswirken. Es ist einfach, einen Stall von Strategien zu schaffen, da der Portfolio-Konstruktionsmechanismus und der Risikomanager leicht modifiziert werden können, um mehrere Systeme zu behandeln. So sollten sie zu Beginn der Gestaltung eines algorithmischen Handelssystems als wesentliche Komponenten betrachtet werden. Die Aufgabe des Portfolio-Bausystems ist es, eine Reihe von gewünschten Trades zu tätigen und die Menge der tatsächlichen Trades zu produzieren, die den Churn minimieren, die Exposition gegenüber verschiedenen Faktoren (wie Sektoren, Assetklassen, Volatilität usw.) aufrechterhalten und die Zuteilung von Kapital zu verschiedenen optimieren Strategien in einem Portfolio. Der Portfolioaufbau reduziert sich häufig auf ein lineares Algebra-Problem (wie z. B. eine Matrixfaktorisierung) und damit ist die Leistung in hohem Maße von der Effektivität der numerischen linearen Algebra-Implementierung abhängig. Gemeinsame Bibliotheken beinhalten uBLAS. LAPACK und NAG für C. MatLab besitzt auch weitgehend optimierte Matrixoperationen. Python nutzt NumPySciPy für solche Berechnungen. Ein häufig neu ausgewogenes Portfolio erfordert eine kompilierte (und gut optimierte) Matrixbibliothek, um diesen Schritt auszuführen, um das Handelssystem nicht zu verschränken. Das Risikomanagement ist ein weiterer äußerst wichtiger Bestandteil eines algorithmischen Handelssystems. Risiko kann in vielen Formen kommen: Erhöhte Volatilität (obwohl dies für bestimmte Strategien als wünschenswert angesehen werden kann), erhöhte Korrelationen zwischen Assetklassen, Gegenpartei-Default, Serverausfälle, Black-Swan-Events und unentdeckte Bugs im Handelscode, um einen Namen zu nennen wenige. Risikomanagementkomponenten versuchen und erwarten die Auswirkungen einer übermäßigen Volatilität und Korrelation zwischen den Assetklassen und ihren nachfolgenden Auswirkungen auf das Handelskapital. Oft reduziert sich dies auf eine Reihe von statistischen Berechnungen wie Monte Carlo Stresstests. Dies ist sehr ähnlich wie die rechnerischen Bedürfnisse einer Derivate-Pricing-Engine und als solche wird CPU-gebunden. Diese Simulationen sind sehr parallelisierbar (siehe unten) und bis zu einem gewissen Grad ist es möglich, Hardware auf das Problem zu werfen. Ausführungssysteme Die Aufgabe des Ausführungssystems ist es, gefilterte Handelssignale aus den Portfoliokonstruktionen und Risikomanagementkomponenten zu erhalten und sie an eine Vermittlung oder andere Marktmittel zu senden. Für die Mehrheit der Einzelhandels-algorithmischen Handelsstrategien handelt es sich dabei um eine API - oder FIX-Verbindung zu einem Brokerage wie Interactive Brokers. Die primären Überlegungen bei der Entscheidung über eine Sprache beinhalten die Qualität der API, die Sprache-Wrapper-Verfügbarkeit für eine API, die Ausführungsfrequenz und den zu erwartenden Schlupf. Die Qualität der API verweist darauf, wie gut dokumentiert es ist, welche Art von Leistung es bietet, ob es sich um eine eigenständige Software handelt, auf die zugegriffen werden kann oder ob ein Gateway kopflos aufgebaut werden kann (d. h. keine GUI). Im Falle von Interactive Brokers muss das Trader WorkStation-Tool in einer GUI-Umgebung ausgeführt werden, um auf ihre API zuzugreifen. Ich musste einmal eine Desktop Ubuntu Edition auf einen Amazon Cloud Server installieren, um interaktive Broker remote zugreifen zu können, rein aus diesem Grund Die meisten APIs stellen eine C andor Java Schnittstelle zur Verfügung. In der Regel ist es Aufgabe der Community, sprachspezifische Wrapper für C, Python, R, Excel und MatLab zu entwickeln. Beachten Sie, dass mit jedem zusätzlichen Plugin verwendet (vor allem API Wrapper) gibt es Spielraum für Bugs, um in das System zu kriechen. Testen Sie immer Plugins dieser Art und stellen Sie sicher, dass sie aktiv gepflegt werden. Ein lohnender Messgerät ist zu sehen, wie viele neue Updates zu einer Codebasis in den letzten Monaten gemacht wurden. Die Ausführungshäufigkeit ist im Ausführungsalgorithmus von größter Bedeutung. Beachten Sie, dass Hunderte von Aufträgen jede Minute gesendet werden können und als solche Leistung kritisch ist. Der Schlupf wird durch ein leistungsstarkes Abwicklungssystem entstehen und dies wird einen dramatischen Einfluss auf die Rentabilität haben. Statisch typisierte Sprachen (siehe unten) wie CJava sind in der Regel optimal für die Ausführung, aber es gibt einen Kompromiss in Entwicklungszeit, Test und Wartungsfreundlichkeit. Dynamisch typisierte Sprachen wie Python und Perl sind jetzt in der Regel schnell genug. Achten Sie stets darauf, dass die Bauteile modular aufgebaut sind (siehe unten), so dass sie als Systemwaage ausgetauscht werden können. Architektonischer Planungs - und Entwicklungsprozess Die Komponenten eines Handelssystems, dessen Frequenz - und Volumenanforderungen wurden oben diskutiert, aber die Systeminfrastruktur ist noch nicht abgedeckt. Diejenigen, die als Einzelhändler handeln oder in einem kleinen Fonds arbeiten, werden wahrscheinlich viele Hüte tragen. Es wird notwendig sein, das Alpha-Modell, das Risikomanagement und die Ausführungsparameter sowie die endgültige Implementierung des Systems abdecken zu können. Bevor wir in spezifische Sprachen eintauchen, wird die Gestaltung einer optimalen Systemarchitektur diskutiert. Trennung von Bedenken Eine der wichtigsten Entscheidungen, die zu Beginn getroffen werden müssen, ist, wie man die Anliegen eines Handelssystems trennen kann. In der Softwareentwicklung bedeutet dies im Wesentlichen, wie man die verschiedenen Aspekte des Handelssystems in separate modulare Komponenten zerlegt. Durch das Belichten von Schnittstellen an jedem der Komponenten ist es einfach, Teile des Systems für andere Versionen auszutauschen, die Leistung, Zuverlässigkeit oder Wartung unterstützen, ohne irgendeinen externen Abhängigkeitscode zu modifizieren. Dies ist die beste Praxis für solche Systeme. Für Strategien bei niedrigeren Frequenzen werden solche Praktiken empfohlen. Für den Hochfrequenzhandel muss das Regelwerk auf Kosten der Optimierung des Systems für noch mehr Leistung ignoriert werden. Ein stärker gekoppeltes System kann wünschenswert sein. Das Erstellen einer Komponentenkarte eines algorithmischen Handelssystems ist einen Artikel an sich wert. Allerdings ist ein optimaler Ansatz, um sicherzustellen, dass es getrennte Komponenten für die historischen und Echtzeit-Marktdateneingaben, Datenspeicherung, Datenzugriffs-API, Backtester, Strategieparameter, Portfolio-Konstruktion, Risikomanagement und automatisierte Ausführungssysteme gibt. Zum Beispiel, wenn der verwendete Datenspeicher derzeit auch unter erheblichen Optimierungsniveaus unterdurchschnittlich ist, kann er mit minimaler Umschreibung auf die Datenaufnahme oder Datenzugriffs-API ausgetauscht werden. So weit wie der Backtester und nachfolgende Komponenten betroffen sind, gibt es keinen Unterschied. Ein weiterer Vorteil von getrennten Komponenten ist, dass es eine Vielzahl von Programmiersprachen im Gesamtsystem verwendet werden kann. Es besteht keine Notwendigkeit, auf eine einzige Sprache beschränkt zu sein, wenn die Kommunikationsmethode der Komponenten sprachunabhängig ist. Dies ist der Fall, wenn sie über TCPIP, ZeroMQ oder ein anderes sprachunabhängiges Protokoll kommunizieren. Als konkretes Beispiel ist der Fall eines Backtesting-Systems zu betrachten, das in C für die Zahl Crunching-Performance geschrieben wird, während die Portfolio-Manager und Ausführungs-Systeme in Python mit SciPy und IBPy geschrieben werden. Leistungsüberlegungen Die Performance ist für die meisten Handelsstrategien von großer Bedeutung. Für höhere Frequenzstrategien ist es der wichtigste Faktor. Die Leistung deckt eine breite Palette von Problemen ab, wie etwa die algorithmische Ausführungsgeschwindigkeit, die Netzwerklatenz, die Bandbreite, die Daten IO, die Konkurrenz und die Skalierung. Jeder dieser Bereiche wird individuell von großen Lehrbüchern abgedeckt, so dass dieser Artikel nur die Oberfläche jedes Themas kratzen wird. Architektur und Sprachwahl werden nun in Bezug auf ihre Auswirkungen auf die Leistung diskutiert. Die vorherrschende Weisheit, wie von Donald Knuth angegeben. Einer der Väter der Informatik, ist die vorzeitige Optimierung die Wurzel allen Übels. Dies ist fast immer der Fall - außer beim Aufbau eines hochfrequenten Trading-Algorithmus Für diejenigen, die sich für niederfrequente Strategien interessieren, ist ein gemeinsamer Ansatz, ein System auf die einfachste Weise zu bauen und nur zu optimieren, wenn Engpässe beginnen zu erscheinen. Profiling-Tools werden verwendet, um festzustellen, wo Engpässe entstehen. Profile können für alle oben aufgeführten Faktoren erstellt werden, entweder in einer MS Windows - oder Linux-Umgebung. Es gibt viele Betriebssystem-und Sprach-Tools zur Verfügung, um dies zu tun, sowie Drittanbieter-Dienstprogramme. Die Sprachwahl wird nun im Rahmen der Performance diskutiert. C, Java, Python, R und MatLab enthalten alle Hochleistungsbibliotheken (entweder als Teil ihres Standards oder extern) für die Grunddatenstruktur und die algorithmische Arbeit. C-Schiffe mit der Standard-Vorlagenbibliothek, während Python NumPySciPy enthält. Gemeinsame mathematische Aufgaben sind in diesen Bibliotheken zu finden und es ist selten von Vorteil, eine neue Implementierung zu schreiben. Eine Ausnahme ist, wenn eine hochgradig angepasste Hardwarearchitektur erforderlich ist und ein Algorithmus umfangreiche Verwendung von proprietären Erweiterungen (wie z. B. benutzerdefinierte Caches) macht. Allerdings verschwendet oft die Neuerung des Rades Zeit, die besser ausgegeben werden könnte, um andere Teile der Handelsinfrastruktur zu entwickeln und zu optimieren. Entwicklungszeit ist vor allem im Kontext von Sohlenentwicklern äußerst wertvoll. Latenz ist oft ein Thema des Ausführungssystems, da die Forschungsinstrumente meist auf derselben Maschine liegen. Für die ersteren kann die Latenzzeit an mehreren Punkten entlang des Ausführungspfades auftreten. Datenbanken müssen konsultiert werden (Disknetwork Latency), Signale müssen generiert werden (Betriebssyste, kernal Messaging Latenz), Handelssignale gesendet (NIC Latenz) und Aufträge verarbeitet (Austausch der internen Latenz des Systems). Für höhere Frequenzoperationen ist es notwendig, sich mit der kernalen Optimierung sowie der Optimierung der Netzwerkübertragung vertraut zu machen. Dies ist ein tiefer Bereich und ist deutlich über den Umfang des Artikels, aber wenn ein UHFT-Algorithmus gewünscht wird dann bewusst sein, die Tiefe des Wissens erforderlich Caching ist sehr nützlich in der Toolkit eines quantitativen Handel Entwickler. Caching bezieht sich auf das Konzept der Speicherung von häufig zugegriffenen Daten in einer Weise, die einen leistungsfähigeren Zugriff ermöglicht, auf Kosten der potentiellen Staleness der Daten. Ein häufiger Anwendungsfall tritt bei der Web-Entwicklung bei der Datenübertragung von einer disk-backed relationalen Datenbank auf und setzt sie in den Speicher. Alle nachfolgenden Anfragen für die Daten müssen nicht auf die Datenbank treffen und so können Leistungssteigerungen erheblich sein. Für Handelssituationen kann das Caching äußerst vorteilhaft sein. Zum Beispiel kann der aktuelle Status eines Strategieportfolios in einem Cache gespeichert werden, bis er neu ausgeglichen wird, so dass die Liste nicht auf jeder Schleife des Handelsalgorithmus regeneriert werden muss. Eine solche Regeneration ist wahrscheinlich eine hohe CPU - oder Festplatten-IO-Operation. Das Caching ist jedoch nicht ohne eigene Probleme. Die Regeneration von Cache-Daten auf einmal, aufgrund der volatilen Natur des Cache-Speichers, kann erhebliche Nachfrage nach Infrastruktur stellen. Ein weiteres Problem ist das Hunde-Stapeln. Wo mehrere Generationen einer neuen Cache-Kopie unter extrem hoher Belastung durchgeführt werden, was zu Kaskadenfehler führt. Die dynamische Speicherzuordnung ist eine teure Bedienung bei der Softwareausführung. So ist es zwingend erforderlich, dass hochleistungsfähige Handelsanwendungen sich bewusst sind, wie Speicher während des Programmablaufs zugewiesen und freigegeben wird. Neuere Sprachstandards wie Java, C und Python führen automatisch eine automatische Garbage Collection durch. Die sich auf die Freigabe des dynamisch zugewiesenen Speichers bezieht, wenn Objekte aus dem Geltungsbereich gehen. Garbage Collection ist äußerst nützlich während der Entwicklung, da es Fehler reduziert und hilft Lesbarkeit. Allerdings ist es für bestimmte Hochfrequenz-Handelsstrategien oftmals suboptimal. Für diese Fälle ist oft eine benutzerdefinierte Garbage Collection erwünscht. In Java, zum Beispiel durch Abstimmung der Garbage Collector und Heap-Konfiguration, ist es möglich, hohe Leistung für HFT-Strategien zu erhalten. C stellt keinen nativen Garbage Collector zur Verfügung und so ist es notwendig, alle Speicherzuweisungen als Teil einer Objektimplementierung zu behandeln. Während potenziell fehleranfällig (potenziell zu baumelnden Zeigern führen) ist es äußerst nützlich, eine feinkörnige Kontrolle darüber zu haben, wie Objekte auf dem Haufen für bestimmte Anwendungen erscheinen. Bei der Auswahl einer Sprache ist zu beachten, wie der Müllsammler arbeitet und ob er modifiziert werden kann, um für einen bestimmten Anwendungsfall zu optimieren. Viele Operationen in algorithmischen Handelssystemen sind der Parallelisierung zugänglich. Dies bezieht sich auf das Konzept der Durchführung mehrerer programmatischer Operationen zur gleichen Zeit, d. h. parallel. So genannte peinlich parallele Algorithmen beinhalten Schritte, die vollständig unabhängig von anderen Schritten berechnet werden können. Bestimmte statistische Operationen wie Monte-Carlo-Simulationen sind ein gutes Beispiel für peinlich parallele Algorithmen, da jede zufällige Zeichnung und nachfolgende Pfadoperation ohne Kenntnis anderer Pfade berechnet werden können. Andere Algorithmen sind nur teilweise parallelisierbar. Fluid-Dynamik-Simulationen sind ein solches Beispiel, wo die Domäne der Berechnung unterteilt werden kann, aber letztlich müssen diese Domänen miteinander kommunizieren und somit sind die Operationen teilweise sequentiell. Parallelisierbare Algorithmen unterliegen dem Amdahls-Gesetz. Die eine theoretische Obergrenze für die Leistungserhöhung eines parallelisierten Algorithmus liefert, wenn sie N getrennten Prozessen (z. B. auf einem CPU-Kern oder einem Thread) unterworfen ist. Die Parallelisierung ist zunehmend wichtiger als Optimierungsmechanismus, da die Prozessor-Taktraten stagniert haben, da neuere Prozessoren viele Kerne enthalten, mit denen parallele Berechnungen durchgeführt werden können. The rise of consumer graphics hardware (predominently for video games) has lead to the development of Graphical Processing Units (GPUs), which contain hundreds of cores for highly concurrent operations. Such GPUs are now very affordable. High-level frameworks, such as Nvidias CUDA have lead to widespread adoption in academia and finance. Such GPU hardware is generally only suitable for the research aspect of quantitative finance, whereas other more specialised hardware (including Field-Programmable Gate Arrays - FPGAs) are used for (U)HFT. Nowadays, most modern langauges support a degree of concurrencymultithreading. Thus it is straightforward to optimise a backtester, since all calculations are generally independent of the others. Scaling in software engineering and operations refers to the ability of the system to handle consistently increasing loads in the form of greater requests, higher processor usage and more memory allocation. In algorithmic trading a strategy is able to scale if it can accept larger quantities of capital and still produce consistent returns. The trading technology stack scales if it can endure larger trade volumes and increased latency, without bottlenecking . While systems must be designed to scale, it is often hard to predict beforehand where a bottleneck will occur. Rigourous logging, testing, profiling and monitoring will aid greatly in allowing a system to scale. Languages themselves are often described as unscalable. This is usually the result of misinformation, rather than hard fact. It is the total technology stack that should be ascertained for scalability, not the language. Clearly certain languages have greater performance than others in particular use cases, but one language is never better than another in every sense. One means of managing scale is to separate concerns, as stated above. In order to further introduce the ability to handle spikes in the system (i. e. sudden volatility which triggers a raft of trades), it is useful to create a message queuing architecture. This simply means placing a message queue system between components so that orders are stacked up if a certain component is unable to process many requests. Rather than requests being lost they are simply kept in a stack until the message is handled. This is particularly useful for sending trades to an execution engine. If the engine is suffering under heavy latency then it will back up trades. A queue between the trade signal generator and the execution API will alleviate this issue at the expense of potential trade slippage. A well-respected open source message queue broker is RabbitMQ . Hardware and Operating Systems The hardware running your strategy can have a significant impact on the profitability of your algorithm. This is not an issue restricted to high frequency traders either. A poor choice in hardware and operating system can lead to a machine crash or reboot at the most inopportune moment. Thus it is necessary to consider where your application will reside. The choice is generally between a personal desktop machine, a remote server, a cloud provider or an exchange co-located server. Desktop machines are simple to install and administer, especially with newer user friendly operating systems such as Windows 78, Mac OSX and Ubuntu. Desktop systems do possess some significant drawbacks, however. The foremost is that the versions of operating systems designed for desktop machines are likely to require rebootspatching (and often at the worst of times). They also use up more computational resources by the virtue of requiring a graphical user interface (GUI). Utilising hardware in a home (or local office) environment can lead to internet connectivity and power uptime problems. The main benefit of a desktop system is that significant computational horsepower can be purchased for the fraction of the cost of a remote dedicated server (or cloud based system) of comparable speed. A dedicated server or cloud-based machine, while often more expensive than a desktop option, allows for more significant redundancy infrastructure, such as automated data backups, the ability to more straightforwardly ensure uptime and remote monitoring. They are harder to administer since they require the ability to use remote login capabilities of the operating system. In Windows this is generally via the GUI Remote Desktop Protocol (RDP). In Unix-based systems the command-line Secure SHell (SSH) is used. Unix-based server infrastructure is almost always command-line based which immediately renders GUI-based programming tools (such as MatLab or Excel) to be unusable. A co-located server, as the phrase is used in the capital markets, is simply a dedicated server that resides within an exchange in order to reduce latency of the trading algorithm. This is absolutely necessary for certain high frequency trading strategies, which rely on low latency in order to generate alpha. The final aspect to hardware choice and the choice of programming language is platform-independence. Is there a need for the code to run across multiple different operating systems Is the code designed to be run on a particular type of processor architecture, such as the Intel x86x64 or will it be possible to execute on RISC processors such as those manufactured by ARM These issues will be highly dependent upon the frequency and type of strategy being implemented. Resilience and Testing One of the best ways to lose a lot of money on algorithmic trading is to create a system with no resiliency . This refers to the durability of the sytem when subject to rare events, such as brokerage bankruptcies, sudden excess volatility, region-wide downtime for a cloud server provider or the accidental deletion of an entire trading database. Years of profits can be eliminated within seconds with a poorly-designed architecture. It is absolutely essential to consider issues such as debuggng, testing, logging, backups, high-availability and monitoring as core components of your system. It is likely that in any reasonably complicated custom quantitative trading application at least 50 of development time will be spent on debugging, testing and maintenance. Nearly all programming languages either ship with an associated debugger or possess well-respected third-party alternatives. In essence, a debugger allows execution of a program with insertion of arbitrary break points in the code path, which temporarily halt execution in order to investigate the state of the system. The main benefit of debugging is that it is possible to investigate the behaviour of code prior to a known crash point . Debugging is an essential component in the toolbox for analysing programming errors. However, they are more widely used in compiled languages such as C or Java, as interpreted languages such as Python are often easier to debug due to fewer LOC and less verbose statements. Despite this tendency Python does ship with the pdb. which is a sophisticated debugging tool. The Microsoft Visual C IDE possesses extensive GUI debugging utilities, while for the command line Linux C programmer, the gdb debugger exists. Testing in software development refers to the process of applying known parameters and results to specific functions, methods and objects within a codebase, in order to simulate behaviour and evaluate multiple code-paths, helping to ensure that a system behaves as it should. A more recent paradigm is known as Test Driven Development (TDD), where test code is developed against a specified interface with no implementation. Prior to the completion of the actual codebase all tests will fail. As code is written to fill in the blanks, the tests will eventually all pass, at which point development should cease. TDD requires extensive upfront specification design as well as a healthy degree of discipline in order to carry out successfully. In C, Boost provides a unit testing framework. In Java, the JUnit library exists to fulfill the same purpose. Python also has the unittest module as part of the standard library. Many other languages possess unit testing frameworks and often there are multiple options. In a production environment, sophisticated logging is absolutely essential. Logging refers to the process of outputting messages, with various degrees of severity, regarding execution behaviour of a system to a flat file or database. Logs are a first line of attack when hunting for unexpected program runtime behaviour. Unfortunately the shortcomings of a logging system tend only to be discovered after the fact As with backups discussed below, a logging system should be given due consideration BEFORE a system is designed. Both Microsoft Windows and Linux come with extensive system logging capability and programming languages tend to ship with standard logging libraries that cover most use cases. It is often wise to centralise logging information in order to analyse it at a later date, since it can often lead to ideas about improving performance or error reduction, which will almost certainly have a positive impact on your trading returns. While logging of a system will provide information about what has transpired in the past, monitoring of an application will provide insight into what is happening right now . All aspects of the system should be considered for monitoring. System level metrics such as disk usage, available memory, network bandwidth and CPU usage provide basic load information. Trading metrics such as abnormal pricesvolume, sudden rapid drawdowns and account exposure for different sectorsmarkets should also be continuously monitored. Further, a threshold system should be instigated that provides notification when certain metrics are breached, elevating the notification method (email, SMS, automated phone call) depending upon the severity of the metric. System monitoring is often the domain of the system administrator or operations manager. However, as a sole trading developer, these metrics must be established as part of the larger design. Many solutions for monitoring exist: proprietary, hosted and open source, which allow extensive customisation of metrics for a particular use case. Backups and high availability should be prime concerns of a trading system. Consider the following two questions: 1) If an entire production database of market data and trading history was deleted (without backups) how would the research and execution algorithm be affected 2) If the trading system suffers an outage for an extended period (with open positions) how would account equity and ongoing profitability be affected The answers to both of these questions are often sobering It is imperative to put in place a system for backing up data and also for testing the restoration of such data. Many individuals do not test a restore strategy. If recovery from a crash has not been tested in a safe environment, what guarantees exist that restoration will be available at the worst possible moment Similarly, high availability needs to be baked in from the start. Redundant infrastructure (even at additional expense) must always be considered, as the cost of downtime is likely to far outweigh the ongoing maintenance cost of such systems. I wont delve too deeply into this topic as it is a large area, but make sure it is one of the first considerations given to your trading system. Choosing a Language Considerable detail has now been provided on the various factors that arise when developing a custom high-performance algorithmic trading system. The next stage is to discuss how programming languages are generally categorised. Type Systems When choosing a language for a trading stack it is necessary to consider the type system . The languages which are of interest for algorithmic trading are either statically - or dynamically-typed . A statically-typed language performs checks of the types (e. g. integers, floats, custom classes etc) during the compilation process. Such languages include C and Java. A dynamically-typed language performs the majority of its type-checking at runtime. Such languages include Python, Perl and JavaScript. For a highly numerical system such as an algorithmic trading engine, type-checking at compile time can be extremely beneficial, as it can eliminate many bugs that would otherwise lead to numerical errors. However, type-checking doesnt catch everything, and this is where exception handling comes in due to the necessity of having to handle unexpected operations. Dynamic languages (i. e. those that are dynamically-typed) can often lead to run-time errors that would otherwise be caught with a compilation-time type-check. For this reason, the concept of TDD (see above) and unit testing arose which, when carried out correctly, often provides more safety than compile-time checking alone. Another benefit of statically-typed languages is that the compiler is able to make many optimisations that are otherwise unavailable to the dynamically - typed language, simply because the type (and thus memory requirements) are known at compile-time. In fact, part of the inefficiency of many dynamically-typed languages stems from the fact that certain objects must be type-inspected at run-time and this carries a performance hit. Libraries for dynamic languages, such as NumPySciPy alleviate this issue due to enforcing a type within arrays. Open Source or Proprietary One of the biggest choices available to an algorithmic trading developer is whether to use proprietary (commercial) or open source technologies. There are advantages and disadvantages to both approaches. It is necessary to consider how well a language is supported, the activity of the community surrounding a language, ease of installation and maintenance, quality of the documentation and any licensingmaintenance costs. The Microsoft stack (including Visual C, Visual C) and MathWorks MatLab are two of the larger proprietary choices for developing custom algorithmic trading software. Both tools have had significant battle testing in the financial space, with the former making up the predominant software stack for investment banking trading infrastructure and the latter being heavily used for quantitative trading research within investment funds. Microsoft and MathWorks both provide extensive high quality documentation for their products. Further, the communities surrounding each tool are very large with active web forums for both. The software allows cohesive integration with multiple languages such as C, C and VB, as well as easy linkage to other Microsoft products such as the SQL Server database via LINQ. MatLab also has many pluginslibraries (some free, some commercial) for nearly any quantitative research domain. There are also drawbacks. With either piece of software the costs are not insignificant for a lone trader (although Microsoft does provide entry-level version of Visual Studio for free). Microsoft tools play well with each other, but integrate less well with external code. Visual Studio must also be executed on Microsoft Windows, which is arguably far less performant than an equivalent Linux server which is optimally tuned. MatLab also lacks a few key plugins such as a good wrapper around the Interactive Brokers API, one of the few brokers amenable to high-performance algorithmic trading. The main issue with proprietary products is the lack of availability of the source code. This means that if ultra performance is truly required, both of these tools will be far less attractive. Open source tools have been industry grade for sometime. Much of the alternative asset space makes extensive use of open-source Linux, MySQLPostgreSQL, Python, R, C and Java in high-performance production roles. However, they are far from restricted to this domain. Python and R, in particular, contain a wealth of extensive numerical libraries for performing nearly any type of data analysis imaginable, often at execution speeds comparable to compiled languages, with certain caveats. The main benefit of using interpreted languages is the speed of development time. Python and R require far fewer lines of code (LOC) to achieve similar functionality, principally due to the extensive libraries. Further, they often allow interactive console based development, rapidly reducing the iterative development process. Given that time as a developer is extremely valuable, and execution speed often less so (unless in the HFT space), it is worth giving extensive consideration to an open source technology stack. Python and R possess significant development communities and are extremely well supported, due to their popularity. Documentation is excellent and bugs (at least for core libraries) remain scarce. Open source tools often suffer from a lack of a dedicated commercial support contract and run optimally on systems with less-forgiving user interfaces. A typical Linux server (such as Ubuntu) will often be fully command-line oriented. In addition, Python and R can be slow for certain execution tasks. There are mechanisms for integrating with C in order to improve execution speeds, but it requires some experience in multi-language programming. While proprietary software is not immune from dependencyversioning issues it is far less common to have to deal with incorrect library versions in such environments. Open source operating systems such as Linux can be trickier to administer. I will venture my personal opinion here and state that I build all of my trading tools with open source technologies. In particular I use: Ubuntu, MySQL, Python, C and R. The maturity, community size, ability to dig deep if problems occur and lower total cost ownership (TCO) far outweigh the simplicity of proprietary GUIs and easier installations. Having said that, Microsoft Visual Studio (especially for C) is a fantastic Integrated Development Environment (IDE) which I would also highly recommend. Batteries Included The header of this section refers to the out of the box capabilities of the language - what libraries does it contain and how good are they This is where mature languages have an advantage over newer variants. C, Java and Python all now possess extensive libraries for network programming, HTTP, operating system interaction, GUIs, regular expressions (regex), iteration and basic algorithms. C is famed for its Standard Template Library (STL) which contains a wealth of high performance data structures and algorithms for free. Python is known for being able to communicate with nearly any other type of systemprotocol (especially the web), mostly through its own standard library. R has a wealth of statistical and econometric tools built in, while MatLab is extremely optimised for any numerical linear algebra code (which can be found in portfolio optimisation and derivatives pricing, for instance). Outside of the standard libraries, C makes use of the Boost library, which fills in the missing parts of the standard library. In fact, many parts of Boost made it into the TR1 standard and subsequently are available in the C11 spec, including native support for lambda expressions and concurrency. Python has the high performance NumPySciPyPandas data analysis library combination, which has gained widespread acceptance for algorithmic trading research. Further, high-performance plugins exist for access to the main relational databases, such as MySQL (MySQLC), JDBC (JavaMatLab), MySQLdb (MySQLPython) and psychopg2 (PostgreSQLPython). Python can even communicate with R via the RPy plugin An often overlooked aspect of a trading system while in the initial research and design stage is the connectivity to a broker API. Most APIs natively support C and Java, but some also support C and Python, either directly or with community-provided wrapper code to the C APIs. In particular, Interactive Brokers can be connected to via the IBPy plugin. If high-performance is required, brokerages will support the FIX protocol . Conclusion As is now evident, the choice of programming language(s) for an algorithmic trading system is not straightforward and requires deep thought. The main considerations are performance, ease of development, resiliency and testing, separation of concerns, familiarity, maintenance, source code availability, licensing costs and maturity of libraries. The benefit of a separated architecture is that it allows languages to be plugged in for different aspects of a trading stack, as and when requirements change. A trading system is an evolving tool and it is likely that any language choices will evolve along with it. Just Getting Started with Quantitative TradingThe LMAX Architecture Over the last few years we keep hearing that the free lunch is over1 - we cant expect increases in individual CPU speed. So to write fast code we need to explicitly use multiple processors with concurrent software. This is not good news - writing concurrent code is very hard. Locks and semaphores are hard to reason about and hard to test - meaning we are spending more time worrying about satisfying the computer than we are solving the domain problem. Various concurrency models, such as Actors and Software Transactional Memory, aim to make this easier - but there is still a burden that introduces bugs and complexity. So I was fascinated to hear about a talk at QCon London in March last year from LMAX. LMAX is a new retail financial trading platform. Its business innovation is that it is a retail platform - allowing anyone to trade in a range of financial derivative products2. A trading platform like this needs very low latency - trades have to be processed quickly because the market is moving rapidly. A retail platform adds complexity because it has to do this for lots of people. So the result is more users, with lots of trades, all of which need to be processed quickly.3 Given the shift to multi-core thinking, this kind of demanding performance would naturally suggest an explicitly concurrent programming model - and indeed this was their starting point. But the thing that got peoples attention at QCon was that this wasnt where they ended up. In fact they ended up by doing all the business logic for their platform: all trades, from all customers, in all markets - on a single thread. A thread that will process 6 million orders per second using commodity hardware.4 Processing lots of transactions with low-latency and none of the complexities of concurrent code - how can I resist digging into that Fortunately another difference LMAX has to other financial companies is that they are quite happy to talk about their technological decisions. So now LMAX has been in production for a while its time to explore their fascinating design. Overall Structure Figure 1: LMAXs architecture in three blobs At a top level, the architecture has three parts business logic processor5 input disruptor output disruptors As its name implies, the business logic processor handles all the business logic in the application. As I indicated above, it does this as a single-threaded java program which reacts to method calls and produces output events. Consequently its a simple java program that doesnt require any platform frameworks to run other than the JVM itself, which allows it to be easily run in test environments. Although the Business Logic Processor can run in a simple environment for testing, there is rather more involved choreography to get it to run in a production setting. Input messages need to be taken off a network gateway and unmarshaled, replicated and journaled. Output messages need to be marshaled for the network. These tasks are handled by the input and output disruptors. Unlike the Business Logic Processor, these are concurrent components, since they involve IO operations which are both slow and independent. They were designed and built especially for LMAX, but they (like the overall architecture) are applicable elsewhere. Business Logic Processor Keeping it all in memory The Business Logic Processor takes input messages sequentially (in the form of a method invocation), runs business logic on it, and emits output events. It operates entirely in-memory, there is no database or other persistent store. Keeping all data in-memory has two important benefits. Firstly its fast - theres no database to provide slow IO to access, nor is there any transactional behavior to execute since all the processing is done sequentially. The second advantage is that it simplifies programming - theres no objectrelational mapping to do. All the code can be written using Javas object model without having to make any compromises for the mapping to a database. Using an in-memory structure has an important consequence - what happens if everything crashes Even the most resilient systems are vulnerable to someone pulling the power. The heart of dealing with this is Event Sourcing - which means that the current state of the Business Logic Processor is entirely derivable by processing the input events. As long as the input event stream is kept in a durable store (which is one of the jobs of the input disruptor) you can always recreate the current state of the business logic engine by replaying the events. A good way to understand this is to think of a version control system. Version control systems are a sequence of commits, at any time you can build a working copy by applying those commits. VCSs are more complicated than the Business Logic Processor because they must support branching, while the Business Logic Processor is a simple sequence. So, in theory, you can always rebuild the state of the Business Logic Processor by reprocessing all the events. In practice, however, that would take too long should you need to spin one up. So, just as with version control systems, LMAX can make snapshots of the Business Logic Processor state and restore from the snapshots. They take a snapshot every night during periods of low activity. Restarting the Business Logic Processor is fast, a full restart - including restarting the JVM, loading a recent snapshot, and replaying a days worth of journals - takes less than a minute. Snapshots make starting up a new Business Logic Processor faster, but not quickly enough should a Business Logic Processor crash at 2pm. As a result LMAX keeps multiple Business Logic Processors running all the time6. Each input event is processed by multiple processors, but all but one processor has its output ignored. Should the live processor fail, the system switches to another one. This ability to handle fail-over is another benefit of using Event Sourcing. By event sourcing into replicas they can switch between processors in a matter of micro-seconds. As well as taking snapshots every night, they also restart the Business Logic Processors every night. The replication allows them to do this with no downtime, so they continue to process trades 247. For more background on Event Sourcing, see the draft pattern on my site from a few years ago. The article is more focused on handling temporal relationships rather than the benefits that LMAX use, but it does explain the core idea. Event Sourcing is valuable because it allows the processor to run entirely in-memory, but it has another considerable advantage for diagnostics. If some unexpected behavior occurs, the team copies the sequence of events to their development environment and replays them there. This allows them to examine what happened much more easily than is possible in most environments. This diagnostic capability extends to business diagnostics. There are some business tasks, such as in risk management, that require significant computation that isnt needed for processing orders. An example is getting a list of the top 20 customers by risk profile based on their current trading positions. The team handles this by spinning up a replicate domain model and carrying out the computation there, where it wont interfere with the core order processing. These analysis domain models can have variant data models, keep different data sets in memory, and run on different machines. Tuning performance So far Ive explained that the key to the speed of the Business Logic Processor is doing everything sequentially, in-memory. Just doing this (and nothing really stupid) allows developers to write code that can process 10K TPS7. They then found that concentrating on the simple elements of good code could bring this up into the 100K TPS range. This just needs well-factored code and small methods - essentially this allows Hotspot to do a better job of optimizing and for CPUs to be more efficient in caching the code as its running. It took a bit more cleverness to go up another order of magnitude. There are several things that the LMAX team found helpful to get there. One was to write custom implementations of the java collections that were designed to be cache-friendly and careful with garbage8. An example of this is using primitive java longs as hashmap keys with a specially written array backed Map implementation ( LongToObjectHashMap ). In general theyve found that choice of data structures often makes a big difference, Most programmers just grab whatever List they used last time rather than thinking which implementation is the right one for this context.9 Another technique to reach that top level of performance is putting attention into performance testing. Ive long noticed that people talk a lot about techniques to improve performance, but the one thing that really makes a difference is to test it. Even good programmers are very good at constructing performance arguments that end up being wrong, so the best programmers prefer profilers and test cases to speculation.10 The LMAX team has also found that writing tests first is a very effective discipline for performance tests. Programming Model This style of processing does introduce some constraints into the way you write and organize the business logic. The first of these is that you have to tease out any interaction with external services. An external service call is going to be slow, and with a single thread will halt the entire order processing machine. As a result you cant make calls to external services within the business logic. Instead you need to finish that interaction with an output event, and wait for another input event to pick it back up again. Ill use a simple non-LMAX example to illustrate. Imagine you are making an order for jelly beans by credit card. A simple retailing system would take your order information, use a credit card validation service to check your credit card number, and then confirm your order - all within a single operation. The thread processing your order would block while waiting for the credit card to be checked, but that block wouldnt be very long for the user, and the server can always run another thread on the processor while its waiting. In the LMAX architecture, you would split this operation into two. The first operation would capture the order information and finish by outputting an event (credit card validation requested) to the credit card company. The Business Logic Processor would then carry on processing events for other customers until it received a credit-card-validated event in its input event stream. On processing that event it would carry out the confirmation tasks for that order. Working in this kind of event-driven, asynchronous style, is somewhat unusual - although using asynchrony to improve the responsiveness of an application is a familiar technique. It also helps the business process be more resilient, as you have to be more explicit in thinking about the different things that can happen with the remote application. A second feature of the programming model lies in error handling. The traditional model of sessions and database transactions provides a helpful error handling capability. Should anything go wrong, its easy to throw away everything that happened so far in the interaction. Session data is transient, and can be discarded, at the cost of some irritation to the user if in the middle of something complicated. If an error occurs on the database side you can rollback the transaction. LMAXs in-memory structures are persistent across input events, so if there is an error its important to not leave that memory in an inconsistent state. However theres no automated rollback facility. As a consequence the LMAX team puts a lot of attention into ensuring the input events are fully valid before doing any mutation of the in-memory persistent state. They have found that testing is a key tool in flushing out these kinds of problems before going into production. Input and Output Disruptors Although the business logic occurs in a single thread, there are a number tasks to be done before we can invoke a business object method. The original input for processing comes off the wire in the form of a message, this message needs to be unmarshaled into a form convenient for Business Logic Processor to use. Event Sourcing relies on keeping a durable journal of all the input events, so each input message needs to be journaled onto a durable store. Finally the architecture relies on a cluster of Business Logic Processors, so we have to replicate the input messages across this cluster. Similarly on the output side, the output events need to be marshaled for transmission over the network. Figure 2: The activities done by the input disruptor (using UML activity diagram notation) The replicator and journaler involve IO and therefore are relatively slow. After all the central idea of Business Logic Processor is that it avoids doing any IO. Also these three tasks are relatively independent, all of them need to be done before the Business Logic Processor works on a message, but they can done in any order. So unlike with the Business Logic Processor, where each trade changes the market for subsequent trades, there is a natural fit for concurrency. To handle this concurrency the LMAX team developed a special concurrency component, which they call a Disruptor 11 . The LMAX team have released the source code for the Disruptor with an open source licence. At a crude level you can think of a Disruptor as a multicast graph of queues where producers put objects on it that are sent to all the consumers for parallel consumption through separate downstream queues. When you look inside you see that this network of queues is really a single data structure - a ring buffer. Each producer and consumer has a sequence counter to indicate which slot in the buffer its currently working on. Each producerconsumer writes its own sequence counter but can read the others sequence counters. This way the producer can read the consumers counters to ensure the slot it wants to write in is available without any locks on the counters. Similarly a consumer can ensure it only processes messages once another consumer is done with it by watching the counters. Figure 3: The input disruptor coordinates one producer and four consumers Output disruptors are similar but they only have two sequential consumers for marshaling and output.12 Output events are organized into several topics, so that messages can be sent to only the receivers who are interested in them. Each topic has its own disruptor. The disruptors Ive described are used in a style with one producer and multiple consumers, but this isnt a limitation of the design of the disruptor. The disruptor can work with multiple producers too, in this case it still doesnt need locks.13 A benefit of the disruptor design is that it makes it easier for consumers to catch up quickly if they run into a problem and fall behind. If the unmarshaler has a problem when processing on slot 15 and returns when the receiver is on slot 31, it can read data from slots 16-30 in one batch to catch up. This batch read of the data from the disruptor makes it easier for lagging consumers to catch up quickly, thus reducing overall latency. Ive described things here, with one each of the journaler, replicator, and unmarshaler - this indeed is what LMAX does. But the design would allow multiple of these components to run. If you ran two journalers then one would take the even slots and the other journaler would take the odd slots. This allows further concurrency of these IO operations should this become necessary. The ring buffers are large: 20 million slots for input buffer and 4 million slots for each of the output buffers. The sequence counters are 64bit long integers that increase monotonically even as the ring slots wrap.14 The buffer is set to a size thats a power of two so the compiler can do an efficient modulus operation to map from the sequence counter number to the slot number. Like the rest of the system, the disruptors are bounced overnight. This bounce is mainly done to wipe memory so that there is less chance of an expensive garbage collection event during trading. (I also think its a good habit to regularly restart, so that you rehearse how to do it for emergencies.) The journalers job is to store all the events in a durable form, so that they can be replayed should anything go wrong. LMAX does not use a database for this, just the file system. They stream the events onto the disk. In modern terms, mechanical disks are horribly slow for random access, but very fast for streaming - hence the tag-line disk is the new tape.15 Earlier on I mentioned that LMAX runs multiple copies of its system in a cluster to support rapid failover. The replicator keeps these nodes in sync. All communication in LMAX uses IP multicasting, so clients dont need to know which IP address is the master node. Only the master node listens directly to input events and runs a replicator. The replicator broadcasts the input events to the slave nodes. Should the master node go down, its lack of heartbeat will be noticed, another node becomes master, starts processing input events, and starts its replicator. Each node has its own input disruptor and thus has its own journal and does its own unmarshaling. Even with IP multicasting, replication is still needed because IP messages can arrive in a different order on different nodes. The master node provides a deterministic sequence for the rest of the processing. The unmarshaler turns the event data from the wire into a java object that can be used to invoke behavior on the Business Logic Processor. Therefore, unlike the other consumers, it needs to modify the data in the ring buffer so it can store this unmarshaled object. The rule here is that consumers are permitted to write to the ring buffer, but each writable field can only have one parallel consumer thats allowed to write to it. This preserves the principle of only having a single writer. 16 Figure 4: The LMAX architecture with the disruptors expanded The disruptor is a general purpose component that can be used outside of the LMAX system. Usually financial companies are very secretive about their systems, keeping quiet even about items that arent germane to their business. Not just has LMAX been open about its overall architecture, they have open-sourced the disruptor code - an act that makes me very happy. Not just will this allow other organizations to make use of the disruptor, it will also allow for more testing of its concurrency properties. Queues and their lack of mechanical sympathy The LMAX architecture caught peoples attention because its a very different way of approaching a high performance system to what most people are thinking about. So far Ive talked about how it works, but havent delved too much into why it was developed this way. This tale is interesting in itself, because this architecture didnt just appear. It took a long time of trying more conventional alternatives, and realizing where they were flawed, before the team settled on this one. Most business systems these days have a core architecture that relies on multiple active sessions coordinated through a transactional database. The LMAX team were familiar with this approach, and confident that it wouldnt work for LMAX. This assessment was founded in the experiences of Betfair - the parent company who set up LMAX. Betfair is a betting site that allows people to bet on sporting events. It handles very high volumes of traffic with a lot of contention - sports bets tend to burst around particular events. To make this work they have one of the hottest database installations around and have had to do many unnatural acts in order to make it work. Based on this experience they knew how difficult it was to maintain Betfairs performance and were sure that this kind of architecture would not work for the very low latency that a trading site would require. As a result they had to find a different approach. Their initial approach was to follow what so many are saying these days - that to get high performance you need to use explicit concurrency. For this scenario, this means allowing orders to be processed by multiple threads in parallel. However, as is often the case with concurrency, the difficulty comes because these threads have to communicate with each other. Processing an order changes market conditions and these conditions need to be communicated. The approach they explored early on was the Actor model and its cousin SEDA. The Actor model relies on independent, active objects with their own thread that communicate with each other via queues. Many people find this kind of concurrency model much easier to deal with than trying to do something based on locking primitives. The team built a prototype exchange using the actor model and did performance tests on it. What they found was that the processors spent more time managing queues than doing the real logic of the application. Queue access was a bottleneck. When pushing performance like this, it starts to become important to take account of the way modern hardware is constructed. The phrase Martin Thompson likes to use is mechanical sympathy. The term comes from race car driving and it reflects the driver having an innate feel for the car, so they are able to feel how to get the best out of it. Many programmers, and I confess I fall into this camp, dont have much mechanical sympathy for how programming interacts with hardware. Whats worse is that many programmers think they have mechanical sympathy, but its built on notions of how hardware used to work that are now many years out of date. One of the dominant factors with modern CPUs that affects latency, is how the CPU interacts with memory. These days going to main memory is a very slow operation in CPU-terms. CPUs have multiple levels of cache, each of which of is significantly faster. So to increase speed you want to get your code and data in those caches. At one level, the actor model helps here. You can think of an actor as its own object that clusters code and data, which is a natural unit for caching. But actors need to communicate, which they do through queues - and the LMAX team observed that its the queues that interfere with caching. The explanation runs like this: in order to put some data on a queue, you need to write to that queue. Similarly, to take data off the queue, you need to write to the queue to perform the removal. This is write contention - more than one client may need to write to the same data structure. To deal with the write contention a queue often uses locks. But if a lock is used, that can cause a context switch to the kernel. When this happens the processor involved is likely to lose the data in its caches. The conclusion they came to was that to get the best caching behavior, you need a design that has only one core writing to any memory location17. Multiple readers are fine, processors often use special high-speed links between their caches. But queues fail the one-writer principle. This analysis led the LMAX team to a couple of conclusions. Firstly it led to the design of the disruptor, which determinedly follows the single-writer constraint. Secondly it led to idea of exploring the single-threaded business logic approach, asking the question of how fast a single thread can go if its freed of concurrency management. The essence of working on a single thread, is to ensure that you have one thread running on one core, the caches warm up, and as much memory access as possible goes to the caches rather than to main memory. This means that both the code and the working set of data needs to be as consistently accessed as possible. Also keeping small objects with code and data together allows them to be swapped between the caches as a unit, simplifying the cache management and again improving performance. An essential part of the path to the LMAX architecture was the use of performance testing. The consideration and abandonment of an actor-based approach came from building and performance testing a prototype. Similarly much of the steps in improving the performance of the various components were enabled by performance tests. Mechanical sympathy is very valuable - it helps to form hypotheses about what improvements you can make, and guides you to forward steps rather than backward ones - but in the end its the testing gives you the convincing evidence. Performance testing in this style, however, is not a well-understood topic. Regularly the LMAX team stresses that coming up with meaningful performance tests is often harder than developing the production code. Again mechanical sympathy is important to developing the right tests. Testing a low level concurrency component is meaningless unless you take into account the caching behavior of the CPU. One particular lesson is the importance of writing tests against null components to ensure the performance test is fast enough to really measure what real components are doing. Writing fast test code is no easier than writing fast production code and its too easy to get false results because the test isnt as fast as the component its trying to measure. Should you use this architecture At first glance, this architecture appears to be for a very small niche. After all the driver that led to it was to be able to run lots of complex transactions with very low latency - most applications dont need to run at 6 million TPS. But the thing that fascinates me about this application, is that they have ended up with a design which removes much of the programming complexity that plagues many software projects. The traditional model of concurrent sessions surrounding a transactional database isnt free of hassles. Theres usually a non-trivial effort that goes into the relationship with the database. Objectrelational mapping tools can help much of the pain of dealing with a database, but it doesnt deal with it all. Most performance tuning of enterprise applications involves futzing around with SQL. These days, you can get more main memory into your servers than us old guys could get as disk space. More and more applications are quite capable of putting all their working set in main memory - thus eliminating a source of both complexity and sluggishness. Event Sourcing provides a way to solve the durability problem for an in-memory system, running everything in a single thread solves the concurrency issue. The LMAX experience suggests that as long as you need less than a few million TPS, youll have enough performance headroom. There is a considerable overlap here with the growing interest in CQRS. An event sourced, in-memory processor is a natural choice for the command-side of a CQRS system. (Although the LMAX team does not currently use CQRS.) So what indicates you shouldnt go down this path This is always a tricky questions for little-known techniques like this, since the profession needs more time to explore its boundaries. A starting point, however, is to think of the characteristics that encourage the architecture. One characteristic is that this is a connected domain where processing one transaction always has the potential to change how following ones are processed. With transactions that are more independent of each other, theres less need to coordinate, so using separate processors running in parallel becomes more attractive. LMAX concentrates on figuring the consequences of how events change the world. Many sites are more about taking an existing store of information and rendering various combinations of that information to as many eyeballs as they can find - eg think of any media site. Here the architectural challenge often centers on getting your caches right. Another characteristic of LMAX is that this is a backend system, so its reasonable to consider how applicable it would be for something acting in an interactive mode. Increasingly web application are helping us get used to server systems that react to requests, an aspect that does fit in well with this architecture. Where this architecture goes further than most such systems is its absolute use of asynchronous communications, resulting in the changes to the programming model that I outlined earlier. These changes will take some getting used to for most teams. Most people tend to think of programming in synchronous terms and are not used to dealing with asynchrony. Yet its long been true that asynchronous communication is an essential tool for responsiveness. It will be interesting to see if the wider use of asynchronous communication in the javascript world, with AJAX and node. js, will encourage more people to investigate this style. The LMAX team found that while it took a bit of time to adjust to asynchronous style, it soon became natural and often easier. In particular error handling was much easier to deal with under this approach. The LMAX team certainly feels that the days of the coordinating transactional database are numbered. The fact that you can write software more easily using this kind of architecture and that it runs more quickly removes much of the justification for the traditional central database. For my part, I find this a very exciting story. Much of my goal is to concentrate on software that models complex domains. An architecture like this provides good separation of concerns, allowing people to focus on Domain-Driven Design and keeping much of the platform complexity well separated. The close coupling between domain objects and databases has always been an irritation - approaches like this suggest a way out. if you found this article useful, please share it. I appreciate the feedback and encouragement


No comments:

Post a Comment