Category: LEAN Engine

Tracking and Managing Orders

Tracking and managing orders is an important part of an algorithmic trading strategy. Intelligent order management encourages discipline and a deep understanding of your algorithm. Through the QuantConnect API you can get order fields, update their values and cancel pending orders. This can be useful for lowering trading costs and improving order fills.

When you place a trade you receive an OrderTicket for you to access the order. This allows you to safely (asynchronously) update and cancel the order while in live trading. In live trading you cannot assume order updates are processed successfully as the brokerage may have already filled the trade.

You can place several types of orders including:

Supported Order Types
Market Order MarketOrder("SPY", 100);
Limit Order var ticket = LimitOrder("SPY", 100, 100.10m);
Stop Market Order var ticket = StopMarketOrder("SPY", 100, 100.10m);
Stop Limit Order var ticket = StopLimitOrder("SPY", 100, 100.12m, 99.5m);
Market On Open Order var ticket = MarketOnOpen("SPY", 100);
Market On Close Order var ticket = MarketOnClose("SPY", 100);

 

Once you have an order ticket you can use it to get order fields:

var currentStopPrice = _ticket.Get(OrderField.StopPrice);

Or update the order fields (LimitPrice, StopPrice, Tag or Quantity):

_ticket.Update(new UpdateOrderFields
{
    LimitPrice = newLongLimit,
    Tag = "Update #" + (longOrder.UpdateRequests.Count + 1)
});

You can also cancel your order if required:

_ticket.Cancel();

In the video below we demonstrate putting it all together to create a moving take-profit order which gradually decreases its profit target as time passes.

Desktop Charting with LEAN

With a few configuration changes you can get desktop charting in LEAN with a HTML5 interface very similar to the one you see in QuantConnect.com. This gives you better visual feedback on your strategy and allows you to improve faster. This tutorial guides you through configuring a desktop charting environment with LEAN.

Local charting (and all local backtesting) requires you to have your own source of data. We provide a way to download FX and CFD data through our API. To get started make sure you have your data in your data folder. By default this is the /Data/ directory relative to your LEAN installation.

Two configuration changes are required for desktop charting to work:

  1. Change the “environment” field to use “backtesting-desktop”. This instructs LEAN to use the configuration settings block at the bottom of the config file.
      "environment": "backtesting-desktop",
  2. Insert your API token and user id into configuration file. This is required for chart streaming.
      // To get your api access token go to quantconnect.com/account
      "job-user-id": "....",
      "api-access-token": "...........",

With those changes in place you can simply run the project and your backtesting chart will appear in a few seconds. For live trading; use the”live-desktop” configuration environment.

If you get the run-time exception “The port configured in config.json is either being used or blocked by a firewall”- This normally means you’ve left the user interface open (you should close it between each run). It can also be because another program is sharing that port. You can fix this by changing the port LEAN transmits the data with the "desktop-http-port" setting.

In the tutorial video below we demonstrate this feature on LEAN:

Consolidating Data to Build Bars

Consolidators are used to combine data together from finer resolutions into larger ones. This can be useful for indicators with specific data requirements or to perform long term analysis in conjunction with short term signals.

Consolidators should be constructed and setup in your Initialize() method; this ensures they are only initialized once. There are three key steps to create and register a consolidator:

  1. Create the consolidator object.
  2. Bind an event handler to handle the new bars.
  3. Register it with the subscription manager to start receiving data.
public class ConsolidatorDemoAlgorithm : QCAlgorithm
{
	public override void Initialize() 
	{
		// backtest parameters
		SetStartDate(2016, 1, 1);         
		SetEndDate(DateTime.Now);
		
		// cash allocation
		SetCash(25000);
		
		//assets or universe selection
		AddEquity("SPY", Resolution.Minute);
		
		//create a consolidator object; for tradebars; for a timespan of 30 minutes
		var thirtyMinutes = new TradeBarConsolidator(TimeSpan.FromMinutes(30));

		//bind event handler to data consolidated event.
		thirtyMinutes.DataConsolidated += OnHalfHour;
		
		//register the consolidator for data.
		SubscriptionManager.AddConsolidator("SPY", thirtyMinutes);
	}
	
	//event handler for data!
	public void OnHalfHour(object sender, TradeBar bar) {
		Debug(Time.ToString("u") + " " + bar);
	}
	
	public override void OnData(Slice data) 
	{ }
}

The LEAN API also has other consolidator types to handle working with Ticks and RenkoBars:

// From tick data sources            
var tickConsolidator = new TickConsolidator(TimeSpan.FromMinutes(30)); 

//from renko bars
var renkoConsolidator = new RenkoConsolidator(TimeSpan.FromMinutes(30)); 

There are two key points to remember:

  1. Request a smaller resolution than what you want to produce.
  2. In backtesting we only know the bar is ready on the next data point; so it may appear like daily bars are triggered at odd times. In live trading they are scanned to be triggered every second at a minimum.

The raw data of QuantConnect is provided in Tick, Minute, Second, Hour or Daily bars. Using these building blocks you can combine data together to get any other resolution of data required.

How do I use the API File Provider?

Ensuring a high data quality is one of the hardest parts of setting reliable backtesting. There are many challenges to ensuring your data is in the right format, free of errors or omissions and historically accurate. We’ve tried to address this for you by opening the LEAN Data Library and letting you download our data. LEAN data is organized into millions of tiny files which can be difficult to put into place manually; but using the API File Provider we provide a way for you to automatically install this into your LEAN project.

Currently we provide forex and cfd data for each of the major vendors we support in tick, second, minute, hour and daily resolution. To request data; go to your data library and specify what you’d like to download.

Data library collection for FXCM EURUSD data

Each data file has a unique URL to download thedata for the day which will get a LEAN formatted CSV zip. By using the API File Downloader we check if you have the filein your data-folder; and if not we attempt to download it from the API. This assumes you have already added the data to your repository through the web interface.

This requires 2 key changes to the config.json file in the QuantConnect.Lean.Launcher Project:

  1. Insert your job-user-id and api-access-token into the relevant config fields. You can find these on your Account page.
  2. Update the data-provider configuration to refer to the APIDataProvider class. This is called QuantConnect.Lean.Engine.DataFeeds.ApiDataProvider.

Check out the video below where we guide you step by step through how to use the API Data Provider.

Free Streaming Live Data with IEX – LEAN Release Notes v2.3.0.3

This releaseadds the IEXDataQueueHandler allowing LEAN users to stream free US equity trades to their strategy; along with numerous bug fixes to the OANDA and FXCM brokerage implementations. Additional regression algorithms were added to automate testing of daily data algorithms. The Interactive Brokersconnection logic was also made more intelligent to fail quickly when thereis an existing TWS connection open.There were no breaking changes in regression tests or the API of LEAN.

Download this release from GitHub.

Features

  • Added IEX IDataQueueHandler for a free live US equity datafeed.
  • Added DailyBasicTemplate regression test algorithm.
  • Dramatically speed up Interactive Brokers connection speed.
  • Scan IBController logs for connection failures and handle them in LEAN.
  • Added FilteredIdentity indicator to filter tick trades and quotes.
  • Created Lean.TryParsePath() to create symbols from a file path.
  • Added ApiFileProvider to download data directly from the API.
  • Upgrade Oanda HistoryProvider to return QuoteBars instead of TradeBars.

Bug Fixes

  • Fix duplicate sampling bug in daily data backtesting.
  • Remove time from daily sample points in backtesting.
  • Properly load existing short positions when launching Interactive Brokers algorithm.
  • Fix issue with indicators that require a quote subscription.
  • Check for valid symbols when getting OANDA or FXCM history request.
  • Ensure logs are only savedonce.

Notes

  • We upgraded LEAN to use JSON.NET v9.0.1. This library is used extensively through LEAN.

Thank you to the community contributors in this release buybackoff andJay-Jay-D!

About LEAN

LEAN aims to empower investors to invest with confidence by using cutting edge algorithmic trading technology. Through the power of open source we are building the world’s best algorithmic trading platform, capable of accurately modeling global markets to give you insight into your strategy. Your trading algorithms can be seamlessly deployed from backtesting into production with no changes or even moved between brokerages. The LEAN user community reaches over 29,000 quants from all over the world.

LEAN supports C#, F#, VB, Java and Python programming languages and can be used in Equity, Forex, CFD, Options and Futures markets. It currently supports live paper trading, or execution by Interactive Brokers, FXCM and Oanda Brokerage.

For more information join the LEAN Community on GitHub.

Release Notes – LEAN v2.3.0.1

This release fixed minor bugs in LEAN to improve its stability and consistency across backtesting and live trading. There were no breaking changes in regression tests or the API of LEAN.

Features

  • Update AlgoSeek data converter to accept input file mask to only convert specific source files.
  • Added IsAssignable to detect assignment orders in backtesting*.
  • Added demonstration algorithm for consolidating futures data.
  • Simplified the basic template options algorithm to demonstrate other tickers.

Bug Fixes

  • Fixed race condition creating fill-forward subscriptions incorrectly resulting in different statistics.
  • Fixed bug in AlgoSeek options data converter when processing massive files.
  • Fixed issue where Interactive Brokers was not connected before making history requests.
  • Updated default history provider for OANDA and FXCM configurations to be the brokerage.
  • Fixed issue where CFD datatype defaulted to Quote; preventing algorithms from receiving data.
  • Fix issue in live trading where multiple threads accessing cashbook killed algorithms.
  • Upgraded FXCM account holdings logic to handle multiple positions of the same ticker.
  • Additional logging in scheduled event manager to help debugging time issues.
  • Refactored options exercise logic.

 

Thank you for the continuing bug reports and assistance from the community! A special shout out to h2o, Denny Caldwell and James Reily for helping us work through some issues!

* Note: Assignment events are not generated by IB in live trading. We are looking into heuristic ways to detect this but currently assignments are not handled in live trading.

About LEAN

LEAN aims to empower investors to invest with confidence by using cutting edge algorithmic trading technology. Through the power of open source we are building the world’s best algorithmic trading platform, capable of accurately modeling global markets to give you insight into your strategy. Trading algorithms can be seamlessly deployed from backtesting into production with no changes or moved between brokerages. The LEAN user community reaches over 28,000 quants from all over the world.

LEAN supports C#, F#, VB, Java and Python programming languages and can be used in Equity, Forex, CFD, Options and Futures markets. It currently supports live paper trading, or execution by Interactive Brokers, FXCM and Oanda Brokerage.

For more information join the LEAN Community on GitHub.

$1 Per Trade, It’s a Quant Revolution

We’re proud to announce live trading with Tradier Brokerage is now public!

In a special offer to QuantConnect users, Tradier Brokerage is offering a limited release of 100 accounts with a flat fee of $1 per trade* with the promo code Quant1. Fees this low on a retail-accessible platform are unparalleled.

Robust Modern API

In our experience Tradier Brokerage has a robust, stateful API with rapid millisecond turn around on order fills giving your algorithm powerful execution. The connection is available in our open source algorithmic trading platform, LEAN.

$1 Per Trade Unlocks Powerful Strategies

Have you ever wanted to explore more active execution strategies? Or trade on sub-$2 shares but been worried fees will eat up your gains? Fees this low can unlock strategies and ideas previously not possible.

Low Account Minimums

To open an account is incredibly simple and only requires a $1,000 account minimum! This dramatically lowers the barrier to launching your live algorithmic trading strategy.

Free Live Trading

If you open and fund an account with Tradier Brokerage you’ll be provided with free live trading on QuantConnect! This gives you all the power of a dedicated 512MB VPS, mobile friendly algorithm command center and SMS notification support for only $1 per trade! This offer is open to all existing QuantConnect clients as well.

Open a Tradier Brokerage Account to Launch your Algorithmic Trading!

Use Promo Code “Quant1” To Open An Account Today
Start your Algorithmic Trading!

 

QuantConnect in combination with Tradier Brokerage $1/trading truly democratizes algorithmic trading. We’re excited about this offer and would love to hear your feedback.

 


November 2016: The $1 trading offerexpired in November 2015 and the Tradier brokerage integration was removedpending the Tradier implementation of a socket based API for improved stability.

Live Trading with Interactive Brokers

We’re very proud to announce our public release of live trading with Interactive Brokers! Now you can seamlessly design and trade your algorithm within QuantConnect.

Automated live trading is one of the most challenging engineering problems in financial technology. It involves controlling large financial resources, while pushing computational power to its limits!

Starting today, you can deploy your algorithms to your Interactive Brokers accounts, using minute, second or tick resolution data for Equities and FOREX. All powered by our open source algorithmic trading platform, LEAN.

Live Trading GUI

QuantConnect live trading comes packed with some impressive functionality to help your trading!

SMS and Email Notifications

Trigger sending emails, web hooks or SMS messages on key events with a single line of code. It is as simple as:
Notify.Sms(phone,message);
Notify.Email(email,subject,message);

Custom Live Data Sources

Using QuantConnect you can connect your algorithm to external data sources and stream updates to your algorithm events. Check out our demo using a Bitcoin REST API.

Runtime Statistics

With runtime statistics you can display custom information in the header of your live GUI to track your key indicators and asset values.

SetRuntimeStatistic("EURUSD", price);
Runtime Statistics

Mobile Control Interface

Control your algorithm on the road with our mobile friendly, HTML5 GUI. You can see full running algorithm charts and trades, or just a summary of your algorithm performance.

Live Mobile Controller

Live Options

Upgrade to Start Live Trading Today with QuantConnect

Open Source Updates

Its been an awesome month for the open-source project with contributions from people all around the world. We love working with the community and seeing LEAN used in ways we can barely imagine!

@kaffeebrauer contributed the Stochastic and OnBalance Indicators
@AlexCatarino implemented the ROC, ROCP and WILR Indicators
@QANTau started implementation of an OANDA Brokerage
@bizcad created a Weighted Moving Average Indicator
@mattmast created the Money Flow Index(MFI) Indicator
@bdilber started working on futures support

Additionally thanks to @ammachado, and @dpallone for documentation fixes, and @willniu for working out our consolidator logic 🙂 The LEAN Engine is growing more powerful by the week.

We’re Raising Capital

We’ve been experiencing some incredible growth and have bold plans for the next 12 months! We are opening an investment round and talking to investors to continue our growth plan.

Open Source Future of Algorithmic Trading

We’re proud to announce, thanks to the support of the community, the LEAN Algorithmic Trading Engine is now 100% open source. You have the freedom to connect any data source, execute through any brokerage and design any algorithm 100% locally.

Moment of our Open Sourcing, Jan 12th 2015

It’s an exciting new frontier for algorithmic trading; through open source QuantConnect is breaking open the traditionally secretive world of algorithmic trading to give you the same powerful tools as major hedge-funds.

Lean is “plug and play“. Running your first backtest takes about 23 seconds.

1. Star/Fork and Download the QuantConnect/LEAN Repo* from GitHub
2. Open Lean Project in Visual Studio (let Nuget download all dependencies)
3. Press F5 to Run Project

Presto - you’ve run your first backtest! Here is a step by step guide for building your first algorithm. You can also design custom indicators, import data for international stock markets and connect with any brokerage. We even ship some data with the repo so you can get started instantly.

Clone LEAN Today to Start Your Journey

Clone LEAN Today to Start Your Journey

We’re incredibly grateful to the QuantConnect pioneers for making this possible. With your support we can build the best algorithmic trading platform in the world. Sustainable, independent and community driven.

More Raw Power

To be profitable you need to iterate quickly. Last week we upgraded our backtest processing servers: you can now run a 10 year, event driven backtest in 33 seconds. Your algorithms are running on beautiful i7x3930’s with 6 cores/12 threads/64GB ram. We are the world’s first cloud-desktop hybrid algorithmic trading platform aiming to give you the best of both worlds; ease of local development and horse power of the cloud.

Dynamic Indicator System

Thanks to some long hours by Michael H we launched an elegant, powerful and dynamic new indicator library. It lets you implement designs quickly and avoids reinventing the wheel. Creating an indicator is only a single line of code! Get started with the sample algorithm.

var rsi = RSI("SPY", 14);
var bb = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily);
if (rsi > 80) {
    SetHoldings("SPY", 1);
} else if (rsi < 20) {
    SetHoldings("SPY", -1);
}
Plot("BB", bb.UpperBand, bb.MiddleBand, bb.LowerBand);
Clone the sample algorithm which implements 15+ indicators.

Bollinger Bands Implementation – Clone the sample algorithm which implements 15+ indicators.

 

© 2017 QuantConnect Blog

Democratizing algorithmic investments Up ↑