SlideShare une entreprise Scribd logo
1  sur  26
Speaker: Dr. Hui Liu
tradingwithIB.com | IBridgePy@gmail.com
28th September, 2016
Trading with Interactive
Brokers using Python
Agenda
• Advantages of Interactive Brokers
• Advantages of Python for trading
• IBridgePy
– Installation
– Connecting to IB
– PythonXY and Spider IDE
– Real time quotes
– Historical data
– Place orders
– An example code of moving average crossing
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Advantages of Interactive Brokers
• IB API to automate trading
• Low trading cost
• Global markets access
• Variety of products: stocks, options, futures,
forex, bonds, ETFs and CFDs
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Advantages of Interactive Brokers
• Easy to learn
• Availability of variety of modules
• Open source
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
IBridgePy
Are you looking for a simple tool to trade with Interactive Brokers API using
Python, instead of using IBPy or Quantopian?
• Python tool to trade with Interactive Brokers
– Flexible
– Easy to use
– Privacy
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Installation
• Follow the link to download IBridgePy to your
local folder and unzip it. Then you will see file
structures like that
• You are good to run your trading algo!
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Connecting to IB
• You need have at least a demo account at Interactive Brokers to try your
algo.
• Download either TWS or IB Gateway to feed your needs
TWS will give you much more information about markets and
interactive ways to communicate with IB
IB Gateway is the better choise if IB-everyday-retart is a concern for
you
• Check ‘IB API’
• Input your credentials and click ‘Login’
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Connecting to IB (2)
• In IB Gateway, -> Configure -> Settings
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Connecting to IB (3)
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
PythonXY
• Python(x,y) is a free scientific and engineering
development software for numerical
computations, data analysis and data
visualization based on Python programming
language, Qt graphical user interfaces and Spyder
interactive scientific development environment.
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Prepare IDE
• ‘View’-> ‘Panes’-> Check ‘Editor’ and ‘Console’
• Add the folder to the Python Path by clicking ‘Tools’ -> ‘PYTHONPATH manager’
-> ‘Add path’ -> choose the folder where you unzip IBridgePy.
• Then, click ‘Close’ to accept it.
• It is preferred to restart the Spider IDE to make sure the Python path is
effective.
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Run a sample code
• Open RUN_ME.py in Spider IDE by clicking ‘File’-> ‘Open’
• You may see Spider show up like the following
You may
edit your
code here
You will
see results
here
• To run the python code, click the green triangle or ‘F5’
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Code structure
• "initialize()" is an built-in method to claim variables.
• It will only be run once
• "handle_data()" is also an built-in method where trading decision is made
• Two inputs are given here (context, data). "Context" contains the variables
claimed in initialize(). "data" is the live feed received either daily or
minutely.
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Run a sample code
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Closer look at RUN_ME.py
• Line 16~ line 19: You may choose one algo that you want to execute by
commenting out others
• Line 20: You account code at IB
• Line 21: How often the function of handle_data(context, data), 60 means
to run it every minute and 1 means to run it every second.
• Line 22: There are 4 levels to show results
– ERROR: only show error messages
– INFO: typical users will use it to know the results of your algo
– DEBUG: you may know more info when you debug your algo
– NOTSET: You will see tremendous info if you really want to know what
is going on Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Three corner stones
• Real time price
• Historical data
• Place order
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Ask for real time quotes
• When you need a real time price, simply call a build-in function of
show_real_time_price
• For most of US stocks and ETF, you can simply put ‘AAPL’ for apple instead
of ‘STK, AAPL, USD’
• For Forex, Future and Options, more info is needed to specify. For
example,
– 'FUT,ES,USD,201503‘
– ‘OPT,AAPL,USD,20150702,133,P,100’
– ‘CASH, EUR, USD’
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Ask for historical data from IB
• Request_data is used to ask all kinds of data form IB server
• To ask for historical data from IB, a parameter “historyData” need to be
specified.
– Selecting the instrument for which the historical data needs to be
obtained, in the above example, SPY, an ETF tracking S&P500 index
– Fixing the granularity (time gap), ‘1 day’
– The period of go-back, ’50 D’ means go back 50 days from today.
– The retrieved historical data are saved in a pandas dataframe that are
saved at hist, an attribute of the DataClass, saved in a dictionary called
data
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Ask for historical data from IB (2)
• Of course you may request historical data from IB from other time period,
at other frequencies
• The request format is defined by IB
https://www.interactivebrokers.com/en/software/api/api.htm
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Ask for historical data from IB (3)
• Request multiple historical data at once
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Place orders
• Place market orders: order(symbol(‘SPY’), 100)
– Place an market
– The target security is SPY
– The action is to BUY 100 shares when n > 0
– Negative number means SELL, -100 = SELL 100 shares
– order_target(symbol(‘SPY’), 100) will adjust positions based on your
holding positions by either BUY or SELL until you hold 100 shares
• Place Limit/Stop orders
– order(symbol(‘SPY’), 100, LimitOrder(213.42)) place a limit order to
BUY 100 shares of SPY at price = $213.42 per share
– order(symbol(‘SPY’), -100, StopOrder(213.42)) place a stop order to
SELL 100 shares of SPY at price = $213.42 per share
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Place orders (2)
• It is highly recommended to follow up on the status of the order you
placed by order_status_monitor()
– orderId is the unique identity of your order requests
– For market orders, you should expect ‘Filled’ as the ending point of
your order request, which means the orders have been executed at IB
– For limit and stop orders, the expected status is ‘Submitted’, which
means the orders have been accepted by IB and waiting for executions
– For high liquidity securities, it won’t take too long ( a few seconds ) to
complete the transactions.
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Place orders (3)
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Moving average crossing
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
Thank You!
If you need help, WE are here !
IBridgePy@gmail.com
tradingwithIB.com
We have highly experienced in implementing
various trading algorithms quickly
Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
SINGAPORE
30 Cecil Street, #19-08,
Prudential Tower,
Singapore – 049712
Phone: +65-9057-8301
INDIA
A-309, Boomerang,
Chandivali Farm Road, Powai,
Mumbai - 400 072
Phone: +91-22-61691400
Learn Automated Trading
Join EPAT™
The Executive Programme in
Algorithmic Trading
Enquire Now!

Contenu connexe

Plus de QuantInsti

Portfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningPortfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningQuantInsti
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An IntroductionQuantInsti
 
Introduction to Systematic Options Trading
Introduction to Systematic Options TradingIntroduction to Systematic Options Trading
Introduction to Systematic Options TradingQuantInsti
 
Competitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingCompetitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingQuantInsti
 
Volatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXVolatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXQuantInsti
 
Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingQuantInsti
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexQuantInsti
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantInsti
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...QuantInsti
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategyQuantInsti
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...QuantInsti
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisQuantInsti
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...QuantInsti
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...QuantInsti
 
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...QuantInsti
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsQuantInsti
 
Risk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationRisk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationQuantInsti
 

Plus de QuantInsti (20)

Portfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningPortfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine Learning
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An Introduction
 
Introduction to Systematic Options Trading
Introduction to Systematic Options TradingIntroduction to Systematic Options Trading
Introduction to Systematic Options Trading
 
Competitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingCompetitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic Trading
 
Volatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXVolatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIX
 
Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail Investing
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX Index
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock Market
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of Cryptocurrencies
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategy
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative Analysis
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
 
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
Backtesting And Live Trading With Interactive Brokers Using Python With Dr. H...
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
 
Risk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth PresentationRisk Management: Maximising Long-Term Growth Presentation
Risk Management: Maximising Long-Term Growth Presentation
 

Dernier

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Dernier (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Trading with Interactive Brokers using Python by Dr. Hui Liu - 28 September 2016

  • 1. Speaker: Dr. Hui Liu tradingwithIB.com | IBridgePy@gmail.com 28th September, 2016 Trading with Interactive Brokers using Python
  • 2. Agenda • Advantages of Interactive Brokers • Advantages of Python for trading • IBridgePy – Installation – Connecting to IB – PythonXY and Spider IDE – Real time quotes – Historical data – Place orders – An example code of moving average crossing Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 3. Advantages of Interactive Brokers • IB API to automate trading • Low trading cost • Global markets access • Variety of products: stocks, options, futures, forex, bonds, ETFs and CFDs Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 4. Advantages of Interactive Brokers • Easy to learn • Availability of variety of modules • Open source Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 5. IBridgePy Are you looking for a simple tool to trade with Interactive Brokers API using Python, instead of using IBPy or Quantopian? • Python tool to trade with Interactive Brokers – Flexible – Easy to use – Privacy Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 6. Installation • Follow the link to download IBridgePy to your local folder and unzip it. Then you will see file structures like that • You are good to run your trading algo! Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 7. Connecting to IB • You need have at least a demo account at Interactive Brokers to try your algo. • Download either TWS or IB Gateway to feed your needs TWS will give you much more information about markets and interactive ways to communicate with IB IB Gateway is the better choise if IB-everyday-retart is a concern for you • Check ‘IB API’ • Input your credentials and click ‘Login’ Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 8. Connecting to IB (2) • In IB Gateway, -> Configure -> Settings Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 9. Connecting to IB (3) Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 10. PythonXY • Python(x,y) is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user interfaces and Spyder interactive scientific development environment. Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 11. Prepare IDE • ‘View’-> ‘Panes’-> Check ‘Editor’ and ‘Console’ • Add the folder to the Python Path by clicking ‘Tools’ -> ‘PYTHONPATH manager’ -> ‘Add path’ -> choose the folder where you unzip IBridgePy. • Then, click ‘Close’ to accept it. • It is preferred to restart the Spider IDE to make sure the Python path is effective. Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 12. Run a sample code • Open RUN_ME.py in Spider IDE by clicking ‘File’-> ‘Open’ • You may see Spider show up like the following You may edit your code here You will see results here • To run the python code, click the green triangle or ‘F5’ Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 13. Code structure • "initialize()" is an built-in method to claim variables. • It will only be run once • "handle_data()" is also an built-in method where trading decision is made • Two inputs are given here (context, data). "Context" contains the variables claimed in initialize(). "data" is the live feed received either daily or minutely. Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 14. Run a sample code Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 15. Closer look at RUN_ME.py • Line 16~ line 19: You may choose one algo that you want to execute by commenting out others • Line 20: You account code at IB • Line 21: How often the function of handle_data(context, data), 60 means to run it every minute and 1 means to run it every second. • Line 22: There are 4 levels to show results – ERROR: only show error messages – INFO: typical users will use it to know the results of your algo – DEBUG: you may know more info when you debug your algo – NOTSET: You will see tremendous info if you really want to know what is going on Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 16. Three corner stones • Real time price • Historical data • Place order Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 17. Ask for real time quotes • When you need a real time price, simply call a build-in function of show_real_time_price • For most of US stocks and ETF, you can simply put ‘AAPL’ for apple instead of ‘STK, AAPL, USD’ • For Forex, Future and Options, more info is needed to specify. For example, – 'FUT,ES,USD,201503‘ – ‘OPT,AAPL,USD,20150702,133,P,100’ – ‘CASH, EUR, USD’ Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 18. Ask for historical data from IB • Request_data is used to ask all kinds of data form IB server • To ask for historical data from IB, a parameter “historyData” need to be specified. – Selecting the instrument for which the historical data needs to be obtained, in the above example, SPY, an ETF tracking S&P500 index – Fixing the granularity (time gap), ‘1 day’ – The period of go-back, ’50 D’ means go back 50 days from today. – The retrieved historical data are saved in a pandas dataframe that are saved at hist, an attribute of the DataClass, saved in a dictionary called data Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 19. Ask for historical data from IB (2) • Of course you may request historical data from IB from other time period, at other frequencies • The request format is defined by IB https://www.interactivebrokers.com/en/software/api/api.htm Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 20. Ask for historical data from IB (3) • Request multiple historical data at once Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 21. Place orders • Place market orders: order(symbol(‘SPY’), 100) – Place an market – The target security is SPY – The action is to BUY 100 shares when n > 0 – Negative number means SELL, -100 = SELL 100 shares – order_target(symbol(‘SPY’), 100) will adjust positions based on your holding positions by either BUY or SELL until you hold 100 shares • Place Limit/Stop orders – order(symbol(‘SPY’), 100, LimitOrder(213.42)) place a limit order to BUY 100 shares of SPY at price = $213.42 per share – order(symbol(‘SPY’), -100, StopOrder(213.42)) place a stop order to SELL 100 shares of SPY at price = $213.42 per share Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 22. Place orders (2) • It is highly recommended to follow up on the status of the order you placed by order_status_monitor() – orderId is the unique identity of your order requests – For market orders, you should expect ‘Filled’ as the ending point of your order request, which means the orders have been executed at IB – For limit and stop orders, the expected status is ‘Submitted’, which means the orders have been accepted by IB and waiting for executions – For high liquidity securities, it won’t take too long ( a few seconds ) to complete the transactions. Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 23. Place orders (3) Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 24. Moving average crossing Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 25. Thank You! If you need help, WE are here ! IBridgePy@gmail.com tradingwithIB.com We have highly experienced in implementing various trading algorithms quickly Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)
  • 26. SINGAPORE 30 Cecil Street, #19-08, Prudential Tower, Singapore – 049712 Phone: +65-9057-8301 INDIA A-309, Boomerang, Chandivali Farm Road, Powai, Mumbai - 400 072 Phone: +91-22-61691400 Learn Automated Trading Join EPAT™ The Executive Programme in Algorithmic Trading Enquire Now!

Notes de l'éditeur

  1. over 100 market centers in 24 countries.
  2. You can trade Any securities, including stock, futures, options, forex and many others,  that Interactive Brokers provides using IBridgePy. You can use Any Python packages that you want to use. You can get Any data sources from anywhere, such as Yahoo and Google. You can utilize tick based data provided by Interactive Brokers to design complicated trading strategies, even high frequency trading strategies. Easy-to-use IBridgePy wrapped up IB API’s complexity behind the scenes and offer you a much simpler solution. You may complete your automated trading strategy within an hour because you don’t need to worry about managing placed trades and pending orders, coding details about requesting historical data and real time quotes, etc. We have taken care of those so that you can focus on developing your strategies. Privacy You have 100% control of your strategies because you run your programs on your computer, not other’s platform.
  3. First, you need to send an email to ibridgepy@gmail.com to request a download link of the newest version of IBridgePy. Later, you will receive a download link in email. After you follow the download link, save the zip file and unzip it into your local folder you will see a folder. It is called IBridgePy. There is no need to build. You can run it as long as you have installed Python. There are many ways to run the python codes. Personally, I use spider IDE because you can download many useful packages in one time.
  4. Spider IDE is highly recommended because you don’t need to install critical packages like pandas, numpy, etc by yourself later. You may adjust the views based on your preferences. I like to have two views: one for codinng, one for results. You may click
  5. In python, you may put a “#” to comment out the code, which means that line wont be run by python interpretor. How often the function of handle_data(context, data), 60 means to run it every minute and 1 means to run it every second. Of course you may choose to run it at other frequencies but you need to learn a little bit more to control the behavioral of your algo
  6. You don’t need to specifically to submit a request to IB server, IBridgePy has alreay taken care of it for you.