Saturday 23 December 2017

Architektura systemu handlowego java


W e l c o m e Witamy w Domu otwartego systemu handlu Java System OJTS (Open Java Trading System) jest wspólną infrastrukturą służącą do tworzenia systemów obrotu giełdowego. Składa się z czterech części: gromadzenia nieprzetworzonych danych przez Internet, rozpoznawania sygnałów transakcyjnych, modułu wizualizacji i modułów umożliwiających połączenie z programowymi interfejsami platform transakcyjnych, takich jak banki. Celem projektów jest dostarczenie samodzielnej czystej wspólnej infrastrukturze Java (niezależnej od platformy) dla programistów systemów handlu. Niektóre aspekty, które należy uwzględnić, to zapewnienie wspólnego, zgodnego z SQL92, schematu bazy danych do przechowywania danych finansowych, wspólnych interfejsów Java w celu wymiany danych między różnymi modułami, wizualizacji surowych danych finansowych i sygnałów handlowych oraz kilku innych wspólnych aspektów potrzebnych do stworzenia ostateczny system transakcyjny. Z powodu mojej pracy i rodziny nie znajduję czasu na poprawianie OJTS. Kontynuuję aktualizację poniższej sekcji linków, która poprowadzi cię do bardziej aktywnych projektów open source java w tym obszarze. W rzeczywistości w wyniku mojego zainteresowania dynamiką rynków akcji rozpocząłem podróż w głębsze szczegóły ekonomii narodowej w celu zrozumienia kursów wymiany walut. Temat ten ostatecznie doprowadził mnie do głębszego studiowania pieniędzy jako jednostki metrycznej, której używamy w ekonomii do mierzenia wartości, sukcesu lub użyteczności. Temat ten okazał się niezwykle interesujący, ale jednocześnie trudno było znaleźć wszelkie informacje na temat funkcjonowania naszego systemu monetarnego. Idź i pytaj ludzi, skąd pochodzą pieniądze, kto je tworzy i co decyduje o ich wartości. Zauważysz, że nawet ludzie, którzy mają tytuł magistra lub doktora nauk prawnych. w ekonomii nie pozna tych szczegółów. Och, tak, odpowiedzą w jakichś tajemniczych terminach technicznych, ale nie będą w stanie narysować prostego diagramu, który nakreśla ten proces. Podobno H. G. Wells powiedział: "Pisanie waluty jest powszechnie uznawane za niewłaściwe, wręcz prawie nieprzyzwoite. Redaktorzy będą błagać pisarza niemal ze łzami o pisanie o pieniądzach, nie dlatego, że jest to temat nieciekawy, ale dlatego, że zawsze był bardzo niepokojący. Proponuję każdemu, kto mieszka w demokratycznym społeczeństwie, przeczytanie tego tematu. Wpływa na nasze codzienne życie w takim stopniu, że nie może być przesadzony Moim zdaniem każdy obywatel demokratycznego kraju na tym świecie powinien wiedzieć, skąd pochodzą nasze pieniądze. Najprawdopodobniej przyszedłeś na tę witrynę internetową, aby szukać narzędzi, które pomogą Ci zwiększyć bogactwo pieniężne. Aby zrozumieć kwotę jednostki monetarnej (niezależnie od tego, czy dolar czy euro) będzie ważnym składnikiem zestawu narzędzi do zarabiania pieniędzy. Jeśli masz mało czasu i tylko możesz sobie pozwolić na przeczytanie jednej książki o tym temacie, proponuję przeczytanie bogactwa, wirtualnego bogactwa i długu Frederika Soddy'ego. Byłem w stanie kupić używaną kopię przez Amazon za 23.48, ale istnieje również wersja online. Potrzebny jest plugin DjVu, aby go przeczytać. Ta książka została wydana pierwotnie w 1929 roku, ale nadal opisuje fakty bardzo dobrze. Nawet jeśli nie zgadzam się z wszystkimi wnioskami Fryderyka Soddy'ego, jego praca jest przyjemnie prowokująca i poprowadzi cię do zadawania właściwych pytań. N e w s Wydania, poprawki i zaktualizowana dokumentacja Ogłosiły zawieszenie aktywnego rozwoju i dodano odniesienia do informacji o naszych systemach pieniężnych (DollarEuro). Dodaj sekcję linków do innych ciekawych projektów systemu handlu java. Badam, jak uczynić OJTS bardziej zgodny z innymi działaniami systemu handlu java. Dokumentacja systemu inwestycyjnego i transakcyjnego Projekt można znaleźć na stronie ITSdoc. org. W witrynie ITSdoc. org dostępna jest nowa wiki, która koncentruje się na dystrybucji wiedzy w dziedzinie systemów inwestycyjnych i handlowych. Ideą ITSdoc. org jest stworzenie platformy współpracy podobnej do wikipedia, która pomaga społeczności w dzieleniu się wiedzą. Otworzono OpenJavaTradingSystem v0.13. Wczoraj wydałem wersję 0.13 biblioteki OpenJavaTradingSystem. Do nowych funkcji należą: Odzyskiwanie danych dotyczących akcji, funduszy i walut z firmy OnVista. Wdrażanie obsługi walut i konwersji. Portfele są wdrażane i możesz pracować z Portfelami w taki sam sposób, jak z pojedynczymi papierowymi zabezpieczeniami. Dodano ogólne ramy stosowania algorytmów do serii czasowych na giełdzie. Przełączono z powłoki interaktywnej SISCScheme do ABCLCommonLisp i jej edytora o nazwie J. Dodano ogólny mechanizm buforowania danych do pamięci podręcznej danych, które zostały już pobrane przez sieć w systemie plików. Plus wiele innych pomniejszych ulepszeń Jeśli jesteś zainteresowany tą nową wersją, powinieneś zacząć od sekcji quickstartscreenshot. Podręcznik nie jest jeszcze aktualizowany, ale może dostarczyć Ci cennych informacji podstawowych, jeśli chcesz korzystać z biblioteki w projekcie. Dokumentacja powinna być wkrótce zaktualizowana. Obecnie nie ma wiele do zrobienia, bo podbijam moją wiedzę o sieciach bayeskich. Zobacz na przykład listę książek na mojej stronie internetowej. Dwa ciekawe projekty w tym zakresie to WEKA i BNJ. Wkrótce będę kontynuować rozwój i zacznę integrować pierwszą inteligencję z systemem. Dziś umieściłem pierwsze wydanie w sekcji plików obszaru pobierania sourceforge. Poza tym zaktualizowałem podręcznik, aby udokumentować interaktywne wykorzystanie projektu za pośrednictwem warstwy schematu SISC. Dla niecierpliwych jest tutaj sekcja quickstartscreenshot, która pozwoli Ci rozpocząć grę. Dokumentacja opisująca elementy projektu. Dokumentacja Java Objects i interfejs Dokumentacja gtgtHTML gtgtPDF Dokumentacja użytkowania gtgtHTML gtgtPDF Dokumentacja systemu inwestycyjno-inwestycyjnego Projekt gtgtITSdoc. org T echnologia Bloki konstrukcyjne stron trzecich używane w tym projekcie Baza danych HSQL Engine (licencja: hsqldblic. txt) HSQLDB to silnik bazy danych dostarczany z aby można było natychmiast zacząć używać OJTS bez instalowania bazy danych osób trzecich. Jeśli jednak planujesz użyć innej bazy danych SQL92, jest to opcja konfiguracji. Castor (licencja: licencja Exolab) Castor to struktura wiążąca dane Open Source dla Javatm. Jest to najkrótsza ścieżka między obiektami Java, dokumentami XML i tabelami relacyjnymi. Castor zapewnia powiązanie Java-to-XML, utrwalanie Java-to-SQL i inne. Castor Doclet (licencja: GNU LGPL v2.1) Doclet Java do generowania mapowania i plików DDL dla Castor JDO i Castor XML. TestMaker (licencja: licencja OpenMobile TestMaker) Z projektu TestMaker do zbierania danych z sieci wykorzystywane są tylko protokoły takie jak HTTP lub HTTPS. jCookie (licencja: GNU LGPL v2.1) Biblioteka jCookie jest niezbędna do działania bibliotek TestMaker. htmlparser (licencja: GNU LGPL v2.1) Biblioteka htmlparser służy do wyodrębniania danych z zasobów sieciowych. ABCLCommonLisp (licencja: GNU GPL v2) ABCL (Armed Bear Common Lisp) służy do implementacji algorytmicznego serca projektu w języku programowania ANSI Common Lisp. JFreeChart (licencja: GNU LGPL v2.1) JFreeChart służy do wizualizacji danych finansowych jako wykresów. JSci (licencja: GNU LGPL v2.1) JSci - naukowe API dla Javy. Czas Joda (licencja: licencja OpenSource dla domowej) Joda Time zastępuje oryginalne klasy JDK Date and Time. L i n k s Odsyłacze do innych projektów Grupa JavaTraders w Google może być najlepszym źródłem informacji na temat innych systemów i narzędzi transakcyjnych opartych na Javie. L icense Warunki korzystania Kodeks projektu jest licencjonowany na warunkach LGPL, a wszystkie dokumenty znajdujące się w tym projekcie są licencjonowane na zasadach FDL. A Java Intra-Day Trading System Te strony internetowe pochodzą z pracy Zrobiłam w systemie handlu wewnątrz-dniowego wdrożonym w Javie. To oprogramowanie działa pod serwerem aplikacji Java Tomcat i obsługuje modele transakcyjne odczytujące strumień danych rynkowych w czasie rzeczywistym. Na podstawie tego strumienia danych oprogramowanie generuje zamówienia kupna i sprzedaży oraz śledzi jego pozycję rynkową. Proszę, nie wysyłaj mi e-maila z pytaniem, które techniki handlowe sprawią, że będziesz bogaty. Wiem dużo o wdrażaniu skomplikowanych systemów oprogramowania i wiem coś o budowaniu systemów handlu na rynku. Ja nadal pracuję dla życia, więc wydaje mi się, że sam nie odkryłem tajnego sosu. Nie mam żadnego niezwykłego rynku juju, aby ci przekazać. Pod pewnymi warunkami rozważę projekty zewnętrzne konsultingowe. Projekt konsultingowy musi być zatwierdzony przez mojego pracodawcę, więc jest trochę napowietrznych w rozpoczęciu pracy (ostatni raz zrobiłem jeden z tych projektów, zajęło to miesiąc na zatwierdzenie). Mogę pracować tylko z obywatelami USA, obywatelami Brytyjskiej Wspólnoty Narodów lub sojusznikami NATO. Pierwszą zasadą dla tych, którzy pracują za stawki godzinowe, jest zarabianie, więc proszę, nie pisz mi sugerując, że pracuję za darmo za udział w twoim przedsięwzięciu. Jestem bardzo doświadczonym inżynierem oprogramowania i informatykiem, a moje godzinne opłaty odzwierciedlają to. tradeengine. tar. gz To jest system transakcyjny, który opracowałem. Posiadam prawa autorskie do tego oprogramowania i nie wolno używać go w żadnym celu komercyjnym bez zgody. Ponadto, nie możesz używać tego oprogramowania bez pozwolenia do jakiegokolwiek obrotu na rynku. Ponieważ nie masz pozwolenia na używanie tego oprogramowania do celów innych niż referencyjne, nie możesz mnie pociągnąć do odpowiedzialności za jakiekolwiek błędy w oprogramowaniu lub problemy z jego użyciem. To oprogramowanie jest nieco przestarzałe. Dostępnych jest teraz znacznie więcej zasobów Java. Chociaż jest to architektura rdzenia, można zaimplementować znacznie lepszy system przy użyciu bieżących zasobów Javy. System handlowy został zaprojektowany do współpracy z systemem handlu kontami Interactive Brokers za pośrednictwem interfejsu Java. Te strony internetowe zawierają uwagi dotyczące projektowania systemu handlu, który opracowałam. Istnieją również notatki dotyczące eksperymentów z niektórymi modelami handlu wewnętrznego w stylu analizy technicznej. System handlu Java jest obsługiwany przez złożoną infrastrukturę oprogramowania. Obejmuje to serwer Apache Tomcat (aplikacja sever), kanały danych w czasie rzeczywistym oraz oprogramowanie wspomagające interakcję z użytkownikiem. Szukając oprogramowania, które potrzebowałbym do obsługi systemu transakcyjnego, stworzyłem te notatki. Ian Kaplan Styczeń, 2009 Ostatnia aktualizacja: listopad 2017 Najlepszy język programowania dla algorytmicznych systemów transakcyjnych Jednym z najczęstszych pytań, jakie otrzymuję w mailboxie QS, jest: Jaki jest najlepszy język programowania dla handlu algorytmicznego. Krótką odpowiedzią jest to, że nie ma najlepszego języka. Należy wziąć pod uwagę parametry strategii, wydajność, modułowość, rozwój, odporność i koszty. W tym artykule przedstawione zostaną niezbędne składniki algorytmicznej architektury systemu handlu i jak decyzje dotyczące implementacji wpływają na wybór języka. Po pierwsze, rozważane będą główne elementy algorytmicznego systemu handlu, takie jak narzędzia badawcze, optymalizator portfela, menedżer ryzyka i silnik wykonawczy. Następnie zostaną zbadane różne strategie handlowe i ich wpływ na projekt systemu. W szczególności omówiona zostanie częstotliwość transakcji i prawdopodobny wolumen transakcji. Po wybraniu strategii handlowej konieczne jest zaprojektowanie całego systemu. Obejmuje to wybór sprzętu, systemu operacyjnego i odporność systemu na rzadkie, potencjalnie katastrofalne zdarzenia. Choć architektura jest rozważana, należy wziąć pod uwagę osiągi - zarówno w odniesieniu do narzędzi badawczych, jak i środowiska wykonawczego. Czym zajmuje się system transakcyjny Zanim zdecydujesz się na najlepszy język do napisania automatycznego systemu transakcyjnego, konieczne jest zdefiniowanie wymagań. Czy system będzie w czystości realizowany Czy system będzie wymagał modułu zarządzania ryzykiem lub modułu budowy portfela Czy system wymaga wysokowydajnego backtesteru W przypadku większości strategii system handlu można podzielić na dwie kategorie: Badania i generowanie sygnału. Badania dotyczą oceny skuteczności strategii w odniesieniu do danych historycznych. Proces oceny strategii handlowej nad poprzednimi danymi rynkowymi jest znany jako testy wstępne. Rozmiar danych i złożoność algorytmiczna będą miały duży wpływ na intensywność obliczeniową backtestera. Prędkość procesora i współbieżność są często czynnikami ograniczającymi optymalizację szybkości wykonywania badań. Generowanie sygnałów polega na generowaniu zestawu sygnałów handlowych z algorytmu i wysyłaniu takich zamówień na rynek, zazwyczaj za pośrednictwo. W niektórych strategiach wymagany jest wysoki poziom wydajności. IO, takie jak przepustowość sieci i opóźnienie, są często czynnikiem ograniczającym optymalizację systemów wykonawczych. Wybór języków dla każdego składnika całego systemu może być zupełnie inny. Typ, częstotliwość i objętość strategii Rodzaj zastosowanej strategii algorytmicznej będzie miał znaczący wpływ na konstrukcję systemu. Konieczne będzie rozważenie handlu na giełdach, łączności z zewnętrznymi dostawcami danych, częstotliwości i wielkości strategii, kompromisu między łatwą rozbudową i optymalizacją wydajności, a także dowolnego niestandardowego sprzętu, w tym niestandardowego miejsca kolokacji serwerów, GPU lub FPGA, które mogą być konieczne. Wybory technologii dla amerykańskiej akcji o niskiej częstotliwości będą znacznie różniły się od strategi handlu arbitrażowego o wysokiej częstotliwości na rynku kontraktów terminowych. Przed wyborem języka wielu dostawców danych musi być oceniane, które odnoszą się do omawianej strategii. Konieczne będzie rozważenie możliwości połączenia się z dostawcą, struktury wszelkich interfejsów API, terminowości danych, wymagań dotyczących pamięci masowej i odporności w sytuacji, gdy sprzedawca przechodzi do trybu offline. Mądry jest też posiadanie szybkiego dostępu do wielu dostawców. Różne instrumenty mają własne wady przechowywania, których przykłady obejmują wiele symboli symboli dla akcji i dat wygaśnięcia kontraktów futures (nie wspominając o konkretnych danych OTC). Należy to uwzględnić w projekcie platformy. Częstotliwość strategii jest prawdopodobnie jednym z największych czynników określających sposób definiowania stosu technologii. Strategie wykorzystujące dane częściej niż drobiazgowo lub po drugie takty wymagają znacznego uwzględnienia pod względem wydajności. Strategia przekraczająca po drugie pręty (to jest dane kleszczowe) prowadzi do projektu opartego na wydajności jako podstawowego wymogu. W przypadku strategii wysokiej częstotliwości konieczne będzie przechowywanie i ocena znacznej ilości danych rynkowych. Oprogramowanie takie jak HDF5 lub kdb są powszechnie używane do tych ról. Aby przetworzyć obszerne ilości danych potrzebnych do aplikacji typu HFT, należy zastosować rozbudowany system backtester i system wykonawczy. CC (prawdopodobnie z pewnym asemblerem) najprawdopodobniej będzie najsilniejszym kandydatem na język. Strategie o bardzo wysokiej częstotliwości będą na pewno wymagały sprzętu niestandardowego, takiego jak układy FPGA, wymianę współrzędnych i tuning interfejsu sieci kernalnetwork. Systemy badawcze Systemy badawcze zazwyczaj obejmują połączenie interaktywnego programowania i zautomatyzowanych skryptów. Ten pierwszy często ma miejsce w środowisku IDE, takim jak Visual Studio, MatLab lub R Studio. Ta ostatnia obejmuje rozległe obliczenia liczbowe w odniesieniu do wielu parametrów i punktów danych. Prowadzi to do wyboru języka zapewniającego proste środowisko testowania kodu, ale zapewnia także wystarczającą wydajność w celu oceny strategii nad wieloma parametrami. Typowe IDE w tej przestrzeni to Microsoft Visual CC, który zawiera rozbudowane narzędzia do debugowania, możliwości uzupełniania kodu (za pośrednictwem Intellisense) i proste przeglądy całego stosu projektu (za pośrednictwem bazy danych ORM, LINQ) MatLab. który jest przeznaczony do rozległej numerycznej algebry liniowej i operacji wektorowych, ale w interaktywny sposób konsolowy R Studio. który zawiera konsolę statystyczną R w pełnoprawnym IDE IDE dla Eclipse IDE w środowisku Java oraz C i pół-własnymi IDEami, takimi jak Enthought Canopy for Python, które zawierają biblioteki analizy danych, takie jak NumPy. SciPy. scikit-learn i pandy w jednym środowisku interaktywnym (konsoli). W przypadku testowania danych numerycznych wszystkie powyższe języki są odpowiednie, chociaż nie jest konieczne użycie GUIIDE, ponieważ kod zostanie wykonany w tle. Podstawową kwestią na tym etapie jest szybkość wykonania. Język skompilowany (np. C) jest często przydatny, jeśli wymiary parametrów testów wstecznych są duże. Należy pamiętać o tym, że należy być ostrożnym wobec takich systemów, jeśli tak jest w przypadku języków interpretowanych, takich jak Python, często wykorzystuje biblioteki o wysokiej wydajności, takie jak NumPypandas do etapu analizy historycznej, w celu utrzymania rozsądnego poziomu konkurencyjności z odpowiednikami skompilowanymi. Ostatecznie język wybrany do analizy historycznej zostanie określony przez specyficzne potrzeby algorytmiczne, a także zakres bibliotek dostępnych w danym języku (więcej na ten temat poniżej). Jednak język używany w przypadku backtestera i środowisk badawczych może być całkowicie niezależny od języka używanego w budowie portfela, zarządzaniu ryzykiem i komponentach wykonawczych, co będzie widoczne. Portfolio Budowa i zarządzanie ryzykiem Komponenty portfela budowy i zarządzania ryzykiem są często pomijane przez handlowców algorytmicznych. To prawie zawsze błąd. Narzędzia te stanowią mechanizm, dzięki któremu kapitał zostanie zachowany. Nie tylko starają się złagodzić liczbę ryzykownych zakładów, ale również zminimalizować spowolnienie transakcji, redukując koszty transakcji. Wyrafinowane wersje tych komponentów mogą mieć znaczący wpływ na jakość i spójność rentowności. Łatwo jest stworzyć stabilną strategię, ponieważ mechanizm budowy portfela i menedżer ryzyka można łatwo zmodyfikować w celu obsługi wielu systemów. Dlatego teŜ naleŜy je uznać za istotne składniki na początku projektu algorytmicznego systemu obrotu. Zadaniem systemu budowania portfela jest zebranie zestawu pożądanych transakcji i wyprodukowanie zestawu rzeczywistych transakcji, które minimalizują churn, utrzymują ekspozycje na różne czynniki (takie jak sektory, klasy aktywów, zmienność itp.) I optymalizują alokację kapitału do różnych strategie w portfolio. Konstrukcja portfela często ogranicza się do problemu algebrai liniowej (np. Współczynnik matrycy), a zatem wydajność jest w dużym stopniu uzależniona od skuteczności dostępnych liczbowych implementacji algebry liniowej. Popularne biblioteki obejmują uBLAS. LAPACK i NAG dla C. MatLab posiada również bardzo zoptymalizowane operacje macierzy. Python wykorzystuje NumPySciPy do takich obliczeń. Często zrekompensowany portfel będzie wymagał skompilowanej (i dobrze zoptymalizowanej) biblioteki macierzowej, aby wykonać ten krok, tak aby nie zawęzić systemu handlu. Zarządzanie ryzykiem jest kolejną bardzo ważną częścią systemu handlu algorytmicznego. Ryzyko może przybierać różne formy: zwiększoną zmienność (chociaż może to być postrzegane jako pożądane w przypadku niektórych strategii), zwiększona korelacja między klasami aktywów, domyślne ustawienia kontrahenta, przerwy w działaniu serwerów, zdarzenia związane z czarnymi łabędziami i niewykryte błędy w kodzie handlowym, aby nadać nazwę kilka. Komponenty zarządzania ryzykiem próbują przewidywać skutki nadmiernej zmienności i korelacji pomiędzy klasami aktywów i ich skutkami na kapitale obrotowym. Często zmniejsza się to do zbioru statystycznych obliczeń, takich jak testy warunków skrajnych Monte Carlo. Jest to bardzo podobne do potrzeb obliczeniowych instrumentu wyceny instrumentów pochodnych i jako taki będzie związany z procesorem. Symulacje te są wysoce równoległe (patrz poniżej) i, do pewnego stopnia, można wyrzucić sprzęt do problemu. Systemy wykonawcze Zadaniem systemu wykonawczego jest odbieranie odfiltrowanych sygnałów handlowych z elementów budowy portfela i zarządzania ryzykiem oraz przesyłanie ich do pośrednictwa lub innego sposobu dostępu do rynku. W przypadku większości strategii handlu algorytmicznego obejmuje to połączenie API lub FIX z brokerem, takim jak Interactive Brokers. Podstawowymi względami przy podejmowaniu decyzji o języku są: jakość interfejsu API, dostępność oprogramowania do zawijania języka dla interfejsu API, częstotliwość wykonywania i przewidywany poślizg. Jakość interfejsu API odnosi się do tego, jak dobrze udokumentowano, jaki jest jej poziom wydajności, niezależnie od tego, czy potrzebny jest dostęp do autonomicznego oprogramowania czy czy brama może zostać utworzona w sposób bezkłowy (tj. Bez GUI). W przypadku Interaktywnych Brokerów narzędzie Trader WorkStation musi być uruchomione w środowisku GUI w celu uzyskania dostępu do ich interfejsu API. Kiedyś musiałem zainstalować wydanie Desktop Ubuntu na serwerze chmurowym Amazon, aby uzyskać zdalny dostęp do Interactive Brokers, wyłącznie z tego powodu Większość interfejsów API zapewnia interfejs C ior Java. Zwykle do społeczności należy przygotowywanie specjalnych opakowań języka C, Python, R, Excel i MatLab. Zauważ, że przy każdej dodatkowej wtyczce (zwłaszcza w przypadku wrapperów API) istnieje możliwość wkradania się błędów do systemu. Zawsze testuj wtyki tego typu i upewnij się, że są aktywnie obsługiwane. Wartym uwagi wskaźnikiem jest sprawdzenie, ile nowych aktualizacji bazy kodowej wykonano w ostatnich miesiącach. Częstotliwość wykonywania ma ogromne znaczenie w algorytmie wykonywania. Warto zauważyć, że setki zamówień mogą być wysyłane co minutę i jako takie są kluczowe. Upadek zostanie poniesiony w wyniku niewłaściwego systemu egzekucyjnego, co będzie miało dramatyczny wpływ na rentowność. Języki w wersji statycznej (patrz poniżej), takie jak CJava, są ogólnie optymalne do wykonania, ale w czasie rozwoju, testowaniu i łatwości konserwacji jest kompromis. Dynamicznie pisane języki, takie jak Python i Perl, są na ogół wystarczająco szybkie. Zawsze upewnij się, że komponenty są zaprojektowane modułowo (patrz poniżej), aby można było je wymieniać podczas skalowania systemu. Proces planowania i rozwoju architektury Składniki systemu transakcyjnego, jego wymagania dotyczące częstotliwości i objętości zostały omówione powyżej, ale infrastruktura systemu nie została jeszcze objęta. Ci, którzy działają jako handlowcy detaliczni lub pracujący w małym funduszu, prawdopodobnie nosić będą wiele kapeluszy. Konieczne będzie objęcie modelu alfa, zarządzanie ryzykiem i parametry realizacji, a także ostateczne wdrożenie systemu. Przed przystąpieniem do konkretnych języków omówimy projekt optymalnej architektury systemu. Oddzielenie obaw Jednym z najważniejszych decyzji, które należy na wstępie podjąć, jest oddzielenie obaw systemu handlowego. W rozwoju oprogramowania oznacza to, jak rozbić różne aspekty systemu handlowego na oddzielne elementy modułowe. Ujawniając interfejsy w każdym z komponentów, łatwo jest zamienić części systemu na inne wersje, które wspomagają wydajność, niezawodność lub konserwację, nie modyfikując żadnego zewnętrznego kodu zależności. Jest to najlepsza praktyka dla takich systemów. W przypadku strategii na niższych częstotliwościach takie praktyki są zalecane. W przypadku handlu bardzo wysoką częstotliwością reguła może być ignorowana kosztem zmodyfikowania systemu, aby uzyskać jeszcze większą wydajność. Może być pożądany system bardziej szczelnie sprzężony. Tworzenie mapy komponentów algorytmicznego systemu handlu jest warte sam w sobie. Jednak optymalnym podejściem jest upewnienie się, że istnieją oddzielne komponenty dla danych historycznych i danych rynkowych w czasie rzeczywistym, przechowywania danych, interfejsu API dostępu do danych, backtestera, parametrów strategii, konstrukcji portfela, zarządzania ryzykiem i systemów automatycznej realizacji. Na przykład, jeśli wykorzystywany magazyn danych jest obecnie nierentowny, nawet przy znacznych poziomach optymalizacji, można go zamienić na minimalny przepis na interfejs API przetwarzania danych lub dostępu do danych. Jeśli chodzi o backtestera i kolejne składniki, nie ma różnicy. Inną zaletą oddzielonych komponentów jest to, że pozwala na użycie różnych języków programowania w całym systemie. Nie ma potrzeby ograniczania się do jednego języka, jeśli metoda komunikacji składników jest niezależna od języka. Będzie tak w przypadku, gdy komunikują się przez TCPIP, ZeroMQ lub inny niezależny od języka protokół. Jako konkretny przykład rozważmy przypadek systemu analizy historycznej napisanego w języku C dla sprawdzania poprawności liczb, podczas gdy menedżer portfela i systemy wykonawcze są napisane w Pythonie przy użyciu SciPy i IBPy. Wydajność Wydajność jest istotnym czynnikiem wpływającym na większość strategii handlowych. W przypadku strategii o większej częstotliwości jest to najważniejszy czynnik. Wydajność obejmuje szeroki zakres zagadnień, takich jak algorytmiczna prędkość wykonywania, opóźnienie sieci, przepustowość, dane we współrzędnych, równoległość równoległości i skalowanie. Każdy z tych obszarów jest indywidualnie pokryty dużymi podręcznikami, więc ten artykuł tylko zarysuje powierzchnię każdego tematu. Architektura i wybór języka będą teraz omawiane pod względem ich wpływu na wydajność. Przeważająca mądrość, jak stwierdziła Donald Knuth. jednym z ojców informatyki, jest to, że przedwczesna optymalizacja jest źródłem wszelkiego zła. Dzieje się tak prawie zawsze - z wyjątkiem budowania algorytmu handlu wysokimi częstotliwościami Dla tych, którzy interesują się strategiami o niższej częstotliwości, wspólnym podejściem jest zbudowanie systemu w najprostszy możliwy sposób i jedynie optymalizacja w miarę pojawiania się wąskich gardeł. Narzędzia profilowania służą do określania wąskich gardeł. Profile można tworzyć ze wszystkich wymienionych powyżej czynników, zarówno w środowisku MS Windows, jak i Linux. Istnieje do tego wiele narzędzi systemu operacyjnego i narzędzi językowych, a także narzędzi innych firm. Wybór języka zostanie teraz omówiony w kontekście wyników. C, Java, Python, R i MatLab zawierają biblioteki wysokiej wydajności (jako część ich standardowych lub zewnętrznych) dla podstawowych struktur danych i pracy algorytmicznej. C jest dostarczany ze Standardową Biblioteką Szablonów, a Python zawiera NumPySciPy. Wspólne zadania matematyczne można znaleźć w tych bibliotekach i rzadko jest korzystne napisanie nowej implementacji. Jedynym wyjątkiem jest potrzeba bardzo wymaganej architektury sprzętowej, a algorytm wykorzystuje rozbudowane rozszerzenia (takie jak niestandardowe pamięci podręczne). Jednak często reinwentaryzacja odpadów z kół, które mogłyby być lepiej wykorzystane do opracowywania i optymalizacji innych części infrastruktury handlowej. Czas opracowywania jest niezwykle cenny, szczególnie w kontekście twórców oprogramowania. Opóźnienie jest często problemem systemu wykonawczego, ponieważ narzędzia badawcze są zwykle umieszczone na tej samej maszynie. W przypadku pierwszego z nich opóźnienie może wystąpić w wielu punktach wzdłuż ścieżki wykonania. Trzeba brać pod uwagę bazy danych (czas oczekiwania na sieć dysków), muszą być generowane sygnały (system operacyjny, opóźnienie przesyłania wiadomości kernal), wysyłane sygnały handlowe (czas oczekiwania na NIC) oraz przetwarzane zamówienia (systemy wewnętrznego opóźnienia wymiany). W przypadku operacji o wyższej częstotliwości konieczne jest dokładne zaznajomienie się z optymalizacją jądra i optymalizacją transmisji sieciowej. Jest to obszar głęboki i znacznie wykracza poza zakres artykułu, ale jeśli pożądany jest algorytm UHFT, należy zdawać sobie sprawę z wymaganej głębokości wiedzy. Buforowanie jest bardzo przydatne w zestawie narzędzi ilościowego programisty handlowego. Buforowanie odnosi się do koncepcji przechowywania często używanych danych w sposób, który pozwala na lepszy dostęp, kosztem potencjalnego stagnacji danych. Przy korzystaniu z danych pochodzących z relacyjnej bazy danych obsługiwanych dyskami często pojawia się powszechny przypadek użycia i umieszczanie go w pamięci. Wszelkie kolejne żądania dotyczące danych nie muszą trafiać do bazy danych, a zatem wzrost wydajności może być znaczący. W przypadku transakcji handlowych buforowanie może być bardzo korzystne. Na przykład aktualny stan portfela strategii może być przechowywany w pamięci podręcznej, dopóki nie zostanie ponownie zrównoważony, tak, że lista nie musi być regenerowana po każdej pętli algorytmu handlowego. Taką regeneracją może być wysoka operacja na procesorze lub dysku IO. Jednak buforowanie nie jest bez problemów. Regeneracja danych z pamięci podręcznej na raz, ze względu na lotność charakteru przechowywania pamięci podręcznej, może powodować znaczne zapotrzebowanie na infrastrukturę. Kolejną kwestią jest palowanie psów. gdzie wiele generacji nowej kopii pamięci podręcznej jest wykonywanych przy bardzo dużym obciążeniu, co prowadzi do awarii kaskadowej. Dynamiczna alokacja pamięci jest kosztownym sposobem wykonywania oprogramowania. Z tego względu konieczne jest, aby aplikacje handlowe o wyższej sprawności były dobrze poinformowane, jak przydziela się pamięć i dezalibrować podczas przepływu programu. Nowsze standardy językowe, takie jak Java, C i Python, wykonują automatyczną kolekcję śmieci. co odnosi się do deallokacji dynamicznie przydzielonej pamięci, gdy obiekty wykraczają poza zakres. Zbieranie śmieci jest niezwykle użyteczne podczas opracowywania, redukuje błędy i ułatwia czytelność. Często jest to jednak nieefektywne pod względem niektórych strategii handlowych o wysokiej częstotliwości. Często jest to pożądane w przypadku niestandardowych zbiorów śmieci. W Javie, na przykład, poprzez dostrojenie konfiguracji garbage-zbieracza i sterty, możliwe jest uzyskanie wysokiej wydajności dla strategii HFT. C nie dostarcza natywnego kolektora śmieci, dlatego konieczne jest, aby wszystkie elementy alokacji pamięci były przypisywane do alokacji pamięci w ramach implementacji obiektów. Chociaż potencjalnie podatne na błędy (potencjalnie prowadzące do zwisających wskaźników) niezwykle przydatne jest precyzyjne sterowanie sposobem, w jaki niektóre przedmioty pojawiają się na stosie. Wybierając język upewnij się, że działa jak zbieracz śmieci i czy można go zmodyfikować w celu optymalizacji w konkretnym przypadku użycia. Wiele operacji w algorytmicznych systemach handlowych podlega równoległości. Odnosi się to do koncepcji wykonywania wielu operacji programowych w tym samym czasie, tj. Równolegle. Tak zwane algorytmy równoległe do embarassingly obejmują kroki, które można obliczyć w pełni niezależnie od innych kroków. Pewne operacje statystyczne, takie jak symulacje Monte Carlo, są dobrym przykładem zawstydzająco równoległych algorytmów, ponieważ każde losowe losowanie i następna operacja ścieżkowa może być obliczana bez znajomości innych ścieżek. Inne algorytmy są tylko częściowo równoległe. Symulacje dynamiki płynów są tego rodzaju przykładem, gdzie domena obliczeń może zostać podzielona, ​​ale ostatecznie te domeny muszą się ze sobą komunikować, a zatem operacje są częściowo sekwencyjne. Algorytmy równoległe podlegają Amdahls Law. który zapewnia teoretyczną górną granicę wzrostu wydajności algorytmu równoległego, gdy podlega N oddzielnym procesom (na przykład w rdzeniu lub wątku procesora). Równoległość stała się coraz ważniejsza jako środek optymalizacji, ponieważ szybkości zegara procesora uległy stagnacji, ponieważ nowsze procesory zawierają wiele rdzeni, z którymi można wykonywać równoległe obliczenia. 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