User:Alexkachanov/Finance/Technologies/Access and Connectivity Providers

SFTI сетевой хайвей предоставляет межбиржевое содинение для трейдеров которым нужна скорость и низкая latency

Latency

edit

Вспомним, как выглядит процесс торговли. Вы 1) получаете рыночные данные, 2) принимаете решение, 3) посылаете ордер на исполнение. На каждый из этих этапов требуется время. Рыночные данные должны достигнуть вашего компьютера, вы должны оценить данные и на основании их принять решение, что по чем продавать или покупать, ваш ордер должен преодолеть сетевое расстояние от вашего компьютера до биржи.

Пункт (2) наиболее изощренные трейдры и инвесторы решают с помощью компьютерных алгоритмов, где компьютер, а не человек принимает решение, основываясь на рыночных данных. Такой способ называется алгоритмической торговлей и является отдельной темой. Что же касается пункта (1) и (2), то здесь вступают в силу законы физики, которые могут привести к задержке (latency).

Задержка (latency) неизбежно возникат из-за того, что по законам физики сигнал не может быть передан быстрее скорости света. Это значит не быстрее 300.000 км.сек, или 300 км. в миллисекунду (299,792,458 метров в сек). То есть расстояние в 300 километров неизбежно отнимает 1 миллисекунду у вашей программы. Причем считается не географическое расстояние, а то расстояние, которое сигнал должен пройти по всем соединениям до места назначения, что может быть значительно больше, чем географическое расстояние.

Примеры:

  • 7 миллисекунд от Нью-Йорка до Чикаго (1149 км. по прямой - 3,83 миллисекунды)
  • 35 миллисекунд - от Восточного до Западного побережья США (3944 км. по прямой - 13,14 миллисекунды)
  • 12 милисекунд - из Лондона во Франкфурта (1008 км. по прямой - 3,36 миллисекунды)

NYSE Technologies Universal Trading Platform

  • 5 milliseconds, 3 milliseconds for data, 1 millisecond TSE colocated
  • 2 milliseconds for order and cancel acknowledgements
  • 650 microseconds roundtrip executions for Nasdaq-listed issues
  • 950 microseconds roundtrip executions for NYSE/ Arca-listed issues

Others

  • LSE: 10 microseconds
  • BATS: 400 microseconds
  • OptionsIT Transatlantic: 34 milliseconds
  • Chi-X: 175 milliseconds, marketable IOC 350 microseconds
  • Nasdaq: 250 milliseconds
  • DirectEdge/29West: Persistent messaging 300-500 microseconds


Время

edit
  • 00:00:00.001 - 1 миллисекунда
  • 00:00:00.000,001 - 1 микросекунда
  • 00:00:00.000,000,001 - 1 наносекунда
  • 00:00:00.000,000,000,001 - 1 пикосекунда

Скрость света

edit

Расстояние - время:

  • 1 фут (30 см) кабеля = 1 наносекунда
  • 1 метр кабеля = 3.3 наносекунды
  • 1 километр = 3.3 микросекунды (1 километр волоконной оптики - 4.76 микросекунд - замедление на 70%)
  • 10 километров = 33 микросекунды (10 километров волоконной оптики - 49 микросекунд - замедление на 70%)
  • от геостационарной орбиты до Земли - 35 786 км = 119 миллисекунды = 0,12 секунды

Время - расстояние:

  • 1 миллисекунда - 300 км. кабеля - 300.000 метров кабеля
  • 1 микросекунда - 300 метров кабеля - 30.000 сантиметров кабеля
  • 1 наносекунда - 1 фут (0.3 метра, т.е. 30 см) кабеля - 1 такт процессора с частотой 1ГГц.
  • один такт 3 ГГц процессора - 10 см. 3 ГГц процессор сделает 3 такта за 1 наносекунду

Задержка приведет к slippage (разница между ценой, которая запустила ваш алгоритм и той ценой, по которой произойдет сделка на бирже). Если задержка большая, то за время реакции вашего алгоритма и предачи ордера на биржу цена может измениться в неблагоприятную сторону (например была совершена крупная сделка которая сильно понизила или повысила цену), и ваш ордер прибудет на биржу слишком поздно, и сделка будет совершена по другой цене, не той, на которую среагировал алгоритм. Так slippage может ощутимо ударить по карману, ваш алгоритм будет покупать и продавать не по той цене, по которой нужно, и введет вас в убытки.

The speed of light is a fundamental constraint of the universe according to the current understanding of the laws of physics. The speed of light in a vacuum is exactly 299,792,458 meters per second, or about 300,000 kilometers per second (186,411 miles per second). The speed of light is as fast as one can move a bit of data from one location to another. Neither the buying power of financial institutions nor equipment vendors’ claims can alter the fundamental laws of physics.

Signals in fiber or copper cables can travel at roughly ~70% of the speed of light. The signals slow down in the cable because of the physical construction of the media. For example, when a light signal travels through a transparent material it slows down due to the interaction with the electrons bound to the atoms in the material; the refractive index implies the slow-down factor relative to vacuum - for glass it is about 1.3 to 1.5. Similarly, when an electrical signal travels in a copper cable, it slows down due to the effects of inductance, capacitance, and resistance of the cable. Practically, the signals can travel in the fiber or copper cables at about 70% of the speed of light, which is 210,000 kilometers per second. Presently, the long distance signal transmission technology is more efficient and economical for fiber cables (optical) than for copper cables (electrical).

It takes ~3.3 microseconds in a vacuum for a signal to propagate 1 kilometer at the speed of light (1 kilometer divided by 300,000 kilometers per second). In fiber optic cables the signal slows down to 70%, so the propagation delay for 1 kilometer is about 4.76 microseconds (1 kilometer divided by 210,000 kilometers per second).

Consider the 4,125 kilometers distance between San Francisco and New York. If a fiber cable were stretched in a straight line, it would take the signal about 19.6 milliseconds (0.0196 seconds) to travel that distance. The round trip for one bit of data going from San Francisco to New York and immediately coming back without any processing delay is about 39.2 milliseconds (0.0392 seconds).

The 39.2 milliseconds round trip from San Francisco to New York can put a financial institution with an algorithmic trading platform in San Francisco out of business. Tabb Group asserts that “… the value of time for a trading desk is decidedly non-linear … if a broker’s electronic trading platform is 5 milliseconds behind the competition, it could lose at least 1% of its flow; that’s $4 million in revenues per millisecond. Up to 10 milliseconds of latency could result in a 10% drop in revenues”.

7 OSI Layers

edit

7. Application 6. Presentation 5. Session

4. Transport TCP protocol делит данные на segments the Achilles heel to TCP is that it waits for the acknowledgement from the previous transmission before sending the next segment. Actually, this would be horribly inefficient, so TCP uses what is called a "sliding window" flow protocol where it simultaneously fills a new segment, while sending an unacknowledged segment, while receiving acknowledgement from the previous segment sent.

The TCP bottleneck is typically alleviated through a variety of techniques, such as turning off segment re-send, modifying window sizes, using a modified version of TCP called SCTP, etc. More recently, with the emergence of multi-core microprocessors, each core can be assigned separate TCP sessions, and then segments are carefully spread across all the sessions in a technique called "TCP striping".

3. Network - IP protocol делит сегменты на пакеты Most of the latency penalty at Layer 3 occurs when a packet first arrives, as its IP address must be looked up, and then the packet forwarded to appropriate port. Address lookup and packet forwarding consume the most power, money, and latency in the IP routers that form the internet as we know it today.

2. MAC-адрес - делит пакеты на фреймы

1. Физический уровень - биты Layer 1 contains one of the largest contributors to latency, propagation delay – or actual time-of-flight of the information through the transport media. The three major sources of delay in getting between two points in a financial district are fiber optic cable, proximity, and transport delays.

Shortening the network’s fiber length often means finding a dark fiber provider that has pieced together a shorter route.

Proximity delay is how close you can get to the available fiber access points

Transport equipment delay is the amount of latency that is added by any and all optical gear that the data encounters as it is transported along the fiber.

WAN: Волоконно-оптическая сеть

edit

Color conversion - The majority of optical transport links today are Wavelength Division Multiplexed (WDM), which means everyone is assigned a color channel. it must first be converted from grey to a color. transponding. If done incorrectly, milliseconds can be incurred here.

An often overlooked feature of color conversion is “muxponding”, or the aggregation of lower speed traffic into a higher speed signal

Optical amplification – A signal traveling down an optical fiber gets smaller and smaller with each kilometer of distance. Optical amplifiers are used to boost the signal as it weakens

Dispersion compensation. Chromatic Dispersion (CD). Tradition-ally, long spools of a special type of fiber called Dispersion Compensating Fiber (DCF) have been used to reverse the smearing of colors. alternative dispersion compensation techniques that remove the need for large spools of DCF – Fiber Bragg Gratings (FBG’s).

Electrical regeneration. Traditional regeneration techniques can add hundreds of microseconds of unnecessary delay.

Each router or switch in the data path adds a finite amount of delay as the packet is received, processed, and then forwarded. Each value-added feature, such as NAT or access lists, can add additional latency. Using features that are supported with hardware assistance will greatly reduce latency. The once disparate worlds of LAN switching and WAN routing have been converging. The data communications industry has gone through a transition from TDMA-based serial lines to high-speed Metro Ethernet. The added benefit from using Metro-Ethernet boxes is that they support hardware-assisted forwarding, which can greatly reduce latency.

Latency with a hardware-assisted switch will be in the 4-to-20 microsecond range. The most reasonable processing delay that you can expect in practice should be 25 microseconds per hop. The processing delay on a software-based router can be considerably higher.

Cut-through switching is often considered as an option to reduce serialization-related delay in a switch. Cut-through switching has diminishing returns with contemporary data rates. The advantage of cut through switching is that the switch can start transmitting the packet out the destination port before it has received the full packet on the incoming port.

With cut-through switching, you save the time it takes to transmit/receive the entire packet. Back in the days of 10 Mbps LAN links this meant a lot. The time it takes to transmit a packet at 10 Mbps is between 51.2 and 1200 microseconds for a 64 or 1500 byte packet. Today, at 1 Gbps, this drops to between 0.512 and 12 microseconds. At 10 Gbps, it further reduces to between 0.0512 and 1.2 microseconds. Table 2 summarizes serialization delay effects associated with various link types for 64- and 1500-byte packet sizes.

Smaller Packets: Less Bandwidth and Compression: Smaller packets will be transmitted over the network faster and therefore will have lower latency. However, many smaller packets require greater network overhead (IP headers and Ethernet headers) than fewer larger packets. Compression has always been a trade-off between using less bandwidth with smaller packets and the CPU cycles to compress and decompress the packets. Today there are efficient compression algorithms that take less time and CPU power than the bandwidth savings associated with sending smaller packets. In a sense, CPU power has now exceeded the speed of light.

Queuing Delay: When packets are coming into a router faster than they can leave, you will have queuing.

Transport Layer and the TCP/IP Stack: Nagle’s algorithm—which is very useful for minimizing network overhead by concatenating packets together—interacts very badly with TCP delayed acknowledgements (another optimization option). Some customers might want to disable Nagle’s algorithm under certain circumstances and most stacks have a way to disable Nagle.

Another factor to consider is socket buffer tuning. The best example this type of tuning is to increase receive UDP buffers. UDP has typically been used for low level query/response work such as Domain Name System (DNS) and Network Time Protocol (NTP). Some of the kernel limits for these buffers were designed in the 1980s when networks ran much slower. These are now outdated and should be increased for today’s networks.

LAN: Ethernet-Infiniband

edit

The pure acquisition cost of Ethernet or Infiniband is roughly the same. Ethernet supports longer distances while Infiniband is typically used for co-location

Shared memory interconnect - <1 μs “Raw packets” on Infiniband - <10 μs SDP on Infiniband - 20 μs TCP over Infiniband - 50 μs TCP/IP on 10 GB Ethernet - 50 μs TCP/IP on 1 GB Ethernet - 100 μs

InfiniBand continues to deliver the lowest latencies (as much as 30% lower than Ethernet-based solutions), and highest scalability

Способы уменьшения latency

edit

Существует четыре способа уменьшить задержку:

  • канал market data: Получать упрощенные рыночные данные от вендора (вендоры стали продавать не только простые данные, но и сверхбыстрые сырые и полу-сырые данные)
  • канал market data: Получать сырые рыночные данные напрямую с биржи (минуя вендора)
  • канал orders: Использовать быстрые протоколы передачи ордеров брокеру или на напрямую на биржу
  • оба канала: Увеличить пропускную способность канала
  • оба канала: Перенести свои машины поближе к рынку
  • Проапгрейдить все свои машины и софт

Получать упрощенные данные от вендора

edit

Получать данные напрямую с биржи (минуя вендора)

edit

Подключаясь к бирже напрямую, минуя дата-вендора, участники рынка мокут выиграть от 150 до 500 миллисекунд. A direct-exchange feed, however, is more complex and more expensive. Firms need to build and maintain a system that cleans, formats and processes data so that it can be distributed throughout the organization.

К бирже напрямую можно подлючиться по обычной сети. Для этого у биржи есть свои собственные службы, которые предоставят оборудование и линию. Это оборудование они привезут к вам в офис и подключат его, вам надо будет только в него воткнуться. Оконечник Service Access Point имеет стандартный сетевой разъем, который и является границей ответственности между вашим оборудованием и оборудованием биржи. Вы отвечаете за то, что воткнуто в Service Access Point, а биржа, за Service Access Point и то что стоит между Service Access Point и компьютерами биржи.

Использовать быстрые протоколы передачи ордеров брокеру или на напрямую на биржу

edit

The orders originate from a buy side or sell side firm and are sent to trading venues like an Exchange or ECN for execution. The most common format for order transport is FIX (Financial Information eXchange—http://www.fixprotocol.org/). The applications which handle FIX messages are called FIX engines and they interface with order management systems (OMS).

An optimization to FIX is called FAST (Fix Adapted for Streaming), which uses a compression schema to reduce message length and, in effect, reduce latency. FAST is targeted more to the delivery of market data and has the potential to become a standard. FAST can also be used as a compression schema for proprietary market data formats.


Перенести свои машины поближе к рынку

edit

Для уменьшения задержки ваша торговая машина должна располагаться как можно ближе к бирже. Это можно сделать двумя способами:

  • поставить машину в том же дата-центре, что и машины самой биржи (co-location). Это самый идеальный вариант, так как соединение будет самым быстрым. Но и самый дорогой. К тому же вам самим придется писать софт, который будет разгребать данные с биржи.
  • поставить машину в дата-центре третьей стороны, которая соединена с биржей по гигабитному каналу (proximity service). Вариант более дешевый, но менее выгодный, так как по сравнению с первым вариантом latency будет чуть выше.
    • компания Savvis (Нью-Йорк) (галерея фото)
    • KVH Trading Avenue - компания в Токио которая из своего дата-центра предлагает доступ к Токийским биржам

В дата-центре биржи ставят машины компании-брокеры (торгующие для себя и для клиентов) и крупные покупатели акций (торгующие для себя), так как они ворочают крупными объемами slippage даже в несколько процентов приведет к потере большой суммы. Машины в дата-центре работают в автономном режиме, владельцы машин ими управляют по так называемому "management каналу", который не такой быстрый, но он и не требуется быть быстрым так как он нужен для простого наблюдения, отчетов и внесения изменений в алгоритмы время от времени.

Выжать что можно из технологий

edit

например при передаче данных вместо медного кабеля использовать волоконнооптический. Оптоволокно потенциально передает сигнал со близко к скорости света. Однако и здесь тоже можно выиграть микросекунды на нюансах:

  • качество оптоволокна (его grade) влияет на скорость - чем лучше качество тем меньше latency сигнала
  • загруженнность кабеля другими сигналами - выбирать волокно в кабеле где передается меньше других конкурирующих сигналов
  • маршрут заложения кабеля тоже влияет на путь, которй надо преодолеть сигналу: если кабель следует географическим изгибам местности и огибает препятствия или следует окольным маршрутом - значит увеличивается путь. Значит надо выбирать кабель, который идет как можно прямее. Некоторые трейдерские компании или вендоры, продающие свои кабеля таким компаниям даже специально прокладывают кабель по наикратчайшей прямой - срывая горы и строя мосты, прорывая тоннели, и все равно идеальной прямой не добиваются, плюс вохникают сложности с получением прав на землю по которой прокладывается кабель
  • сама структура кабеля тоже играет важную роль - если кабель состоит из нескольких витков оптоволокна, то сигнал который идет по внешнему витку будет преодолевать большее расстояние по простым законам геометрии - значит если хочется выжать максимум из имеющегося кабеля надо договориться с владельцем кабеля пускать свой сигнал по внутреннему витку, который ближе к центру сечения кабеля, см.: Low Signal Latency in Optical Fiber Networks
  • отказаться от кабеля вообще и если позволяют расстояния - использовать микроволновую передачу сигнала с помощью коротко-волновых радио-передатчиков миллиметрового диапазона в направление прямой видимости, позволяет достигать скорости передачи данных до 20 наносекунд. Millimeter wave radios are being used in trading for a variety of reasons. To begin with, they are faster than microwave radios, as they communicate from one radio to another at speeds as low as 20 nanoseconds, round trip. On top of this speed benefi t, they are able to accommodate more bandwidth on their respective wave or spectral frequency. Literally, the spectrum is physically larger at 80GhZ than at 6GhZ. Most microwave networks carry around 150Mb of traffi c; by contrast a millimeter wave installation can sustain up to 2Gb of data—13 times the amount of bandwidth. Microwaves in trading were developed for the Chicago–to–New York corridor. Chicago to New York, and London to Frankfurt are important to the trading set. Asia is just beginning the process; Latin America and Russia are clearly on the horizon.
  • Enter the TCP/IP offload engine, or TOE. The TOE card, as it’s often known, takes care of moving data between the network and memory, freeing up the CPU to do other things.
  • использование специальных сетевых карт Solarflare / Melanox
  • Any number of computing functions traditionally done on a CPU are potential candidates for moving off the core. The TMX юMessage Switch offered by the already mentioned Tervela, for example, provides an entire pub-sub messaging bus implemented in hardware.
  • GPU cannot perform the complex computational tasks that a CPU can. But it can perform simple tasks, and it can perform a gazillion of them all at once, or in parallel. As such, there are plenty of computational tasks in HFT that are not good candidates for GPGPU. But some of the work behind HFT is just perfectly suited for it. One such job is the pricing of an option using a method known as Monte Carlo simulation (MCS).
  • обработка данных прямо на Ethernet switch - новые коммутаторы (Arista) поставляются с FPGA схемами, куда можно зашить свои программы; есть еще также Ethernet switch, которые работают на Линуксе и позволяют запускать свои программы на этом линкусе, т.е. делать торговую систему прямо на коммутаторе, а не на отдельном компьютере

Ultra-low-latency switches: Mainstream switch manufacturers such as:

  • Arista Networks,
  • Brocade,
  • Cisco Systems,
  • Juniper Networks,
  • Mellanox Technologies and
  • NetScout Systems

all offer ultra-low-latency switches designed for high-performance trading networks

Измерение latency

edit

Addressing the latency issue is a complex problem, requiring a holistic approach that identifies all sources of latency and applies different technologies at different layers of the system.

The main requirements for Latency Monitoring Service are:

  • Sub-millisecond granularity of measurements
  • Near-real time visibility without adding latency to the trading traffic
  • Ability to differentiate application processing latency from network transit latency
  • Ability to handle high message rates
  • Provide a programmatic interface for trading applications to receive latency data, thus enabling algorithmic trading engines to adapt to changing conditions
  • Correlate network events with application events for troubleshooting purposes

Traditional network monitoring tools operate with minutes or seconds granularity. Next-generation trading platforms, especially those supporting algorithmic trading, require latencies less than 5 ms and extremely low levels of packet loss. On a Gigabit LAN, a 100 ms microburst can cause 10,000 transactions to be lost or excessively delayed.

Соединения между тремя финансовыми центрами: Нью-Йорк, Чикаго, Лондон.

Для арбитражеров важно подключения к биржам Нью-Йорка, где торгуются акции, и к биржам Чикаго, где торгуются деривативы по этим акциям. В случае расхождения цен возникает арбитраж, и если поторопиться, можно сорвать заработать бесплатные деньги. С 2008 года Spread Networks потратила 2 года чтобы проделать прямой канал между Нью-Йорком и Чикаго и проложить по нему волоконно-оптический кабель. Между Чикаго по старому кабелю получается 825 миль и сигнал идет 13.3 миллисекунды. Благодаря спрямлению пути удалось сократить расстояние на 100 миль и на 3 миллисекунды. Прокладка такого кабеля стоила по оценкам 300 миллионов долларов. Spread Networks сдает каналы кабеля в аренду. Рядовая аренда кабеля стоит например у Allied Fiber 1.2 миллиона долларов на 20 лет, плюс ежегодная плата за серверное место в дата-центре. Spread Networks благодаря сокращенному пути легко может брать за аренду в 8 раз больше.

The state of the art connection between London and New York for some years was Global Crossing’s AC‐1 transatlantic cable, with one‐way transmissions with approximately 65 milliseconds of latency. However, Hibernia Atlantic spent some $300 million laying a transatlantic fiber optic cable that allows for one‐way latencies of 59.6 milliseconds. This translates into a latency reduction of approximately five milliseconds.7 The line was activated in May 2012, and reportedly was sold out far in advance to a handful of trading customers.

Ссылки

edit

Access

edit

super-DMA: One example of a super-DMA system is the Chi-Velocity product launched by pan-European multilateral trading facility (MTF) Chi-X Europe last October. Dubbed ‘sponsored direct market access’, the Chi-X solution incorporates a risk management layer that is hosted next to the MTF’s matching engine and which the broker can licence.

Server Sites

edit

Illinois

edit
  • Chicago Lakeside (Equinix; 350 Cermak Boulevard, Chicago, IL): Chicago Mercantile Exchange (CME), Intercontinental Exchange (ICE)
  • Chicago Loop (CBOE: 400 S. LaSalle Street, Chicago, IL): Chicago Board Options Exchange (CBOE)

New Jersey

edit
  • Carteret (Verizon: 1400 Federal Boulevard, Carteret, NJ): NASDAQ Stock Market, NASDAQ Options Market, NASDAQ PHLX Options
  • Mahwah (NYSE Technologies: 1600 MacArthur Boulevard, Mahwah, NJ): NYSE Stocks, NYSE AMEX Options, NYSE Arca Options, CTA/OPRA (market data)
  • Secaucus (Equinix: 755 Secaucus Rd Secaucus, NJ): International Securities Exchange (ISE), Boston Options Exchange (BOX), Direct Edge, Chicago Board Options Exchange (C2)
  • Weehawken (800 Harbour Boulevard Weehawken, NJ): BATS Stock, BATS Options