* Reformat/cleanup OptionStrategies This file was breaking pretty much every style convention in LEAN. There are other things that should be addressed in here that weren't, such as passing non-argument names as argument names for ArgumentException, as well as preferring constructors over property initializer syntax, but such changes aren't being made to keep this commit strictly reformatting instead of refactoring. Added braces and reformatted long lines to make code more legible. * Add abstract base class for OptionStrategy Option/UnderlyingLegData This allows us to create either or and later use the Invoke method to push it into the appropriate list on OptionStrategy. * Replace O(n) option contract search with 2 O(1) TryGetValue calls A better improvement would be resolving the correct symbol in the strategy, but this immediate change is instead just focused on removing the O(n) search inside a loop. * Add BinaryComparison and supporting methods in ExpressionBuilder We're going to use these binary comparisons to make it possible to create ad-hoc queries against a collection of symbols. Using these expressions, along with type supporting composition of these expression, we'll be able to define predicates that can declaratively define how to match an option strategy with an algorithms current holdings. * Make GetValueOrDefault defaultValue optional Was receiving ambiguous invocations leading to neading to invoke this method explicitly (LinqExtensions.GetValueOrDefault) instead of being able to use it as an extension method. Making the default value optional seems to have resolved this ambiguity, leading to cleaner code in the OptionPositionCollection (forthcoming) * Add OptionPosition and OptionPositionCollection OptionPositionCollection aims to provide a single coherent interface for querying an algorithm's option contract positions and the underlying equity's position in a performant, immutable way. The immutability of the type is necessary for how the options matcher will operate. We need to recursively evaluate potential matches, each step down the stack removing positions from the collection consumed by each leg matched. This will enable parallelism of the solution as well as simplifying the mental model for understanding due to not needing to track mutations to the collection instance. * Add Option test class for easily creating option symbol objects * Add OptionStrategyLegPredicate and OptionStrategyLegDefinition The definition is a composition of predicates, and each predicate supports matching against a set of pre-existing legs and a current position being checked for the next leg (this leg). In addition to the matching functionality, it also supports filtering the OptionPositionCollection, which is where much of the work for resolving potential option strategies is done. By successively filtering the OptionPositionCollection through successive application of predicates, we wil end up with a small set of remaining positions that can be individually evaluated for best margin impacts. All of this effectively unrolls into a giant evaluation tree. Because of this inherent structure, common in combinatorial optimization, the OptionPositionCollection is an immutable type to support concurrent evaluations of different branches of the tree. For large position collections this will dramatically improve strategy resolution times. Finally, the interface between the predicate and the positions collection is purposefully thin and provides a target for future optimizations. * Add OptionStrategyDefinition and OptionStrategyDefinitions pre-defined definitions The OptionStrategyDefinition is a definitional object provided a template and functions used to match algorithm holdings (via OptionPositionCollection) to this definition. The definition defines a particular way in which option positions can be combined in order to achieve a more favorable margin requirement, thereby allowing the algorithm to hold more positions than otherwise possible. This ties into the existing OptionStrategy classes and the end result of the matching process will be OptionStrategy instances definiing all strategies matched according to the provided definitions. * Add OptionStrategyMatcher and Options class, w/ supporting types OptionStrategyMatcherOptions aims to provide some knobs and dials to control how the matcher behaves, and more importantly, which positions get prioritized when matching. Prioritization is controlled via two different enumerators, one controller which definitions are matched first and the other controller which positions are matched first. Still unimplemented, is computing multiple solutions and running the provided objective function to determine the best match. When this gets implemented, we'll also want to implement the timer. For anyone looking to implement these features, please talk with Michael Handschuh as there's a particular way of representing these types of combinatorial solutions (a 3D tree) that can be used as a variation of the linear simplex method for optimizing combinatorial problems. * OptionStrategyMatcher: Address PR review comments * Ensure created OptionStrategy legs all have the same multiplier Each leg definition match gets it's own multiplier which indicates the maximum number of times we matched that particular leg. When we finish matching all legs, we pick the smallest multiplier from all the legs in the definition and use that as the definition's multiplier. When we go to create the OptionStrategy object we MUST make sure we're using the multiplier from the definition and not from the individual legs. This change fixes this issue and also provides a guard clause to ensure that we're not trying to use a multiplier larger than what was matched. * Add XML docs for OptionStrategyDefinitions from OptionStrategies
Lean Home - https://www.quantconnect.com/lean | Documentation | Download Zip | Docker Hub
Introduction
Lean Engine is an open-source algorithmic trading engine built for easy strategy research, backtesting and live trading. We integrate with common data providers and brokerages so you can quickly deploy algorithmic trading strategies.
The core of the LEAN Engine is written in C#; but it operates seamlessly on Linux, Mac and Windows operating systems. It supports algorithms written in Python 3.6 or C#. Lean drives the web-based algorithmic trading platform QuantConnect.
Proudly Sponsored By
Want your company logo here? Sponsor LEAN to be part of radically open algorithmic-trading innovation.
QuantConnect is Hiring!
Join the team and solve some of the most difficult challenges in quantitative finance. If you are passionate about algorithmic trading we'd like to hear from you. The below roles are open in our Seattle, WA office. When applying, make sure to mention you came through GitHub:
-
Senior UX Developer: Collaborate with QuantConnect to develop a world-leading online experience for a community of developers from all over the world.
-
Technical Writers: Help us improve the QuantConnect and LEAN documentation with hands-on tutorials with how to use all the adaptors LEAN offers, and how to set up trading locally.
-
Quantitative Development Intern: If you are a recent or current graduate with a knack for quantitative finance, consider applying for an internship!
System Overview
The Engine is broken into many modular pieces which can be extended without touching other files. The modules are configured in config.json as set "environments". Through these environments, you can control LEAN to operate in the mode required.
The most important plugins are:
-
Result Processing (IResultHandler)
Handle all messages from the algorithmic trading engine. Decide what should be sent, and where the messages should go. The result processing system can send messages to a local GUI, or the web interface.
-
Datafeed Sourcing (IDataFeed)
Connect and download the data required for the algorithmic trading engine. For backtesting this sources files from the disk, for live trading, it connects to a stream and generates the data objects.
-
Transaction Processing (ITransactionHandler)
Process new order requests; either using the fill models provided by the algorithm or with an actual brokerage. Send the processed orders back to the algorithm's portfolio to be filled.
-
Realtime Event Management (IRealtimeHandler)
Generate real-time events - such as the end of day events. Trigger callbacks to real-time event handlers. For backtesting, this is mocked-up a works on simulated time.
-
Algorithm State Setup (ISetupHandler)
Configure the algorithm cash, portfolio and data requested. Initialize all state parameters required.
These are all configurable from the config.json file in the Launcher Project.
Installation Instructions
We recommend using the docker image. This is perfectly configured to run out of the box without interfering with your development environment. You can pull this image with docker pull quantconnect/lean
Refer to the following readme files for a detailed guide regarding using our docker image with your local IDE:
To install locally, download the zip file with the latest master and unzip it to your favorite location. Alternatively, install Git and clone the repo:
git clone https://github.com/QuantConnect/Lean.git
cd Lean
macOS
- Install Visual Studio for Mac
- Open
QuantConnect.Lean.slnin Visual Studio
Visual Studio will automatically start to restore the Nuget packages. If not, in the menu bar, click Project > Restore NuGet Packages.
- In the menu bar, click
Run > Start Debugging.
Alternatively, run the compiled exe file. First, in the menu bar, click Build > Build All, then:
cd Lean/Launcher/bin/Debug
mono QuantConnect.Lean.Launcher.exe
Linux (Debian, Ubuntu)
- Install Mono:
sudo apt-get update && sudo rm -rf /var/lib/apt/lists/*
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
echo "deb http://download.mono-project.com/repo/ubuntu stable-xenial/snapshots/5.12.0.226 main" > /etc/apt/sources.list.d/mono-xamarin.list && \
apt-get update && apt-get install -y binutils mono-complete ca-certificates-mono mono-vbnc nuget referenceassemblies-pcl && \
apt-get install -y fsharp && rm -rf /var/lib/apt/lists/* /tmp/*
If you get this error on the last command:
Unable to locate package referenceassemblies-pcl,
run the following command (it works on current version of Ubuntu - 17.10):
echo "deb http://download.mono-project.com/repo/ubuntu xenial main" | sudo tee /etc/apt/sources.list.d/mono-official.list
sudo apt-get update
sudo apt-get install -y binutils mono-complete ca-certificates-mono referenceassemblies-pcl fsharp
- Install Nuget
sudo apt-get update && sudo apt-get install -y nuget
- Restore NuGet packages then compile:
nuget restore QuantConnect.Lean.sln
msbuild QuantConnect.Lean.sln
If you get: "Error initializing task Fsc: Not registered task Fsc." -> sudo apt-get upgrade mono-complete
If you get: "XX not found" -> Make sure Nuget ran successfully, and re-run if neccessary.
If you get: "Confirm ... '.../QuantConnect.XX.csproj.*.props' is correct, and that the file exists on disk." -> Ensure that your installation path is free of reserved characters
If you get other errors that lead to the failure of your building, please refer to the commands in "DockerfileLeanFoundation" file for help.
- Run the compiled
exefile:
cd Launcher/bin/Debug
mono ./QuantConnect.Lean.Launcher.exe
- Interactive Brokers set up details
Make sure you fix the ib-tws-dir and ib-controller-dir fields in the config.json file with the actual paths to the TWS and the IBController folders respectively.
If after all you still receive connection refuse error, try changing the ib-port field in the config.json file from 4002 to 4001 to match the settings in your IBGateway/TWS.
Windows
- Install Visual Studio
- Open
QuantConnect.Lean.slnin Visual Studio - Build the solution by clicking Build Menu -> Build Solution (this should trigger the Nuget package restore)
- Press
F5to run
Nuget packages not being restored is the most common build issue. By default Visual Studio includes NuGet, if your installation of Visual Studio (or your IDE) cannot find DLL references, install Nuget, run nuget on the solution and re-build the Solution again.
Python Support
A full explanation of the Python installation process can be found in the Algorithm.Python project.
Local-Cloud Hybrid Development.
You can develop in your IDE and synchronize to the cloud with Skylight. For more information please see the Skylight Home.
Issues and Feature Requests
Please submit bugs and feature requests as an issue to the Lean Repository. Before submitting an issue please read others to ensure it is not a duplicate.
Mailing List
The mailing list for the project can be found on LEAN Forum. Please use this to request assistance with your installations and setup questions.
Contributors and Pull Requests
Contributions are warmly very welcomed but we ask you to read the existing code to see how it is formatted, commented and ensure contributions match the existing style. All code submissions must include accompanying tests. Please see the contributor guide lines.
All accepted pull requests will get a 2mo free Prime subscription on QuantConnect. Once your pull-request has been merged write to us at support@quantconnect.com with a link to your PR to claim your free live trading. QC <3 Open Source.
Acknowledgements
The open-sourcing of QuantConnect would not have been possible without the support of the Pioneers. The Pioneers formed the core 100 early adopters of QuantConnect who subscribed and allowed us to launch the project into open source.
Ryan H, Pravin B, Jimmie B, Nick C, Sam C, Mattias S, Michael H, Mark M, Madhan, Paul R, Nik M, Scott Y, BinaryExecutor.com, Tadas T, Matt B, Binumon P, Zyron, Mike O, TC, Luigi, Lester Z, Andreas H, Eugene K, Hugo P, Robert N, Christofer O, Ramesh L, Nicholas S, Jonathan E, Marc R, Raghav N, Marcus, Hakan D, Sergey M, Peter McE, Jim M, INTJCapital.com, Richard E, Dominik, John L, H. Orlandella, Stephen L, Risto K, E.Subasi, Peter W, Hui Z, Ross F, Archibald112, MooMooForex.com, Jae S, Eric S, Marco D, Jerome B, James B. Crocker, David Lypka, Edward T, Charlie Guse, Thomas D, Jordan I, Mark S, Bengt K, Marc D, Al C, Jan W, Ero C, Eranmn, Mitchell S, Helmuth V, Michael M, Jeremy P, PVS78, Ross D, Sergey K, John Grover, Fahiz Y, George L.Z., Craig E, Sean S, Brad G, Dennis H, Camila C, Egor U, David T, Cameron W, Napoleon Hernandez, Keeshen A, Daniel E, Daniel H, M.Patterson, Asen K, Virgil J, Balazs Trader, Stan L, Con L, Will D, Scott K, Barry K, Pawel D, S Ray, Richard C, Peter L, Thomas L., Wang H, Oliver Lee, Christian L.

