Skip to content

Instantly share code, notes, and snippets.

@ystrohanov
Last active January 17, 2024 16:15
Show Gist options
  • Save ystrohanov/26b493620c3e85a64a0caf9fdd7573af to your computer and use it in GitHub Desktop.
Save ystrohanov/26b493620c3e85a64a0caf9fdd7573af to your computer and use it in GitHub Desktop.
"""
Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
import sys
from ibapi.contract import *
class ContractSamples:
""" Usually, the easiest way to define a Stock/CASH contract is through
these four attributes. """
@staticmethod
def EurGbpFx():
#! [cashcontract]
contract = Contract()
contract.symbol = "EUR"
contract.secType = "CASH"
contract.currency = "GBP"
contract.exchange = "IDEALPRO"
#! [cashcontract]
return contract
@staticmethod
def Index():
#! [indcontract]
contract = Contract()
contract.symbol = "DAX"
contract.secType = "IND"
contract.currency = "EUR"
contract.exchange = "DTB"
#! [indcontract]
return contract
@staticmethod
def CFD():
#! [cfdcontract]
contract = Contract()
contract.symbol = "IBDE30"
contract.secType = "CFD"
contract.currency = "EUR"
contract.exchange = "SMART"
#! [cfdcontract]
return contract
@staticmethod
def EuropeanStock():
contract = Contract()
contract.symbol = "SIE"
contract.secType = "STK"
contract.currency = "EUR"
contract.exchange = "SMART"
return contract
@staticmethod
def OptionAtIse():
contract = Contract()
contract.symbol = "BPX"
contract.secType = "OPT"
contract.currency = "USD"
contract.exchange = "ISE"
contract.lastTradeDateOrContractMonth = "20160916"
contract.right = "C"
contract.strike = 65
contract.multiplier = "100"
return contract
@staticmethod
def BondWithCusip():
#! [bondwithcusip]
contract = Contract()
# enter CUSIP as symbol
contract.symbol= "912828C57"
contract.secType = "BOND"
contract.exchange = "SMART"
contract.currency = "USD"
#! [bondwithcusip]
return contract
@staticmethod
def Bond():
#! [bond]
contract = Contract()
contract.conId = 15960357
contract.exchange = "SMART"
#! [bond]
return contract
@staticmethod
def MutualFund():
#! [fundcontract]
contract = Contract()
contract.symbol = "VINIX"
contract.secType = "FUND"
contract.exchange = "FUNDSERV"
contract.currency = "USD"
#! [fundcontract]
return contract
@staticmethod
def Commodity():
#! [commoditycontract]
contract = Contract()
contract.symbol = "XAUUSD"
contract.secType = "CMDTY"
contract.exchange = "SMART"
contract.currency = "USD"
#! [commoditycontract]
return contract
@staticmethod
def USStock():
#! [stkcontract]
contract = Contract()
contract.symbol = "IBKR"
contract.secType = "STK"
contract.currency = "USD"
#In the API side, NASDAQ is always defined as ISLAND in the exchange field
contract.exchange = "ISLAND"
#! [stkcontract]
return contract
@staticmethod
def USStockWithPrimaryExch():
#! [stkcontractwithprimary]
contract = Contract()
contract.symbol = "MSFT"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
#Specify the Primary Exchange attribute to avoid contract ambiguity
#(there is an ambiguity because there is also a MSFT contract with primary exchange = "AEB")
contract.primaryExchange = "ISLAND"
#! [stkcontractwithprimary]
return contract
@staticmethod
def USStockAtSmart():
contract = Contract()
contract.symbol = "IBKR"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
return contract
@staticmethod
def USOptionContract():
#! [optcontract_us]
contract = Contract()
contract.symbol = "GOOG"
contract.secType = "OPT"
contract.exchange = "SMART"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "20170120"
contract.strike = 615
contract.right = "C"
contract.multiplier = "100"
#! [optcontract_us]
return contract
@staticmethod
def OptionAtBOX():
#! [optcontract]
contract = Contract()
contract.symbol = "GOOG"
contract.secType = "OPT"
contract.exchange = "BOX"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "20170120"
contract.strike = 615
contract.right = "C"
contract.multiplier = "100"
#! [optcontract]
return contract
""" Option contracts require far more information since there are many
contracts having the exact same attributes such as symbol, currency,
strike, etc. This can be overcome by adding more details such as the
trading class"""
@staticmethod
def OptionWithTradingClass():
#! [optcontract_tradingclass]
contract = Contract()
contract.symbol = "SANT"
contract.secType = "OPT"
contract.exchange = "MEFFRV"
contract.currency = "EUR"
contract.lastTradeDateOrContractMonth = "20190621"
contract.strike = 7.5
contract.right = "C"
contract.multiplier = "100"
contract.tradingClass = "SANEU"
#! [optcontract_tradingclass]
return contract
""" Using the contract's own symbol (localSymbol) can greatly simplify a
contract description """
@staticmethod
def OptionWithLocalSymbol():
#! [optcontract_localsymbol]
contract = Contract()
#Watch out for the spaces within the local symbol!
contract.localSymbol = "C DBK DEC 20 1600"
contract.secType = "OPT"
contract.exchange = "DTB"
contract.currency = "EUR"
#! [optcontract_localsymbol]
return contract
""" Dutch Warrants (IOPTs) can be defined using the local symbol or conid
"""
@staticmethod
def DutchWarrant():
#! [ioptcontract]
contract = Contract()
contract.localSymbol = "B881G"
contract.secType = "IOPT"
contract.exchange = "SBF"
contract.currency = "EUR"
#! [ioptcontract]
return contract
""" Future contracts also require an expiration date but are less
complicated than options."""
@staticmethod
def SimpleFuture():
#! [futcontract]
contract = Contract()
contract.symbol = "ES"
contract.secType = "FUT"
contract.exchange = "GLOBEX"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "201803"
#! [futcontract]
return contract
"""Rather than giving expiration dates we can also provide the local symbol
attributes such as symbol, currency, strike, etc. """
@staticmethod
def FutureWithLocalSymbol():
#! [futcontract_local_symbol]
contract = Contract()
contract.secType = "FUT"
contract.exchange = "GLOBEX"
contract.currency = "USD"
contract.localSymbol = "ESU6"
#! [futcontract_local_symbol]
return contract
@staticmethod
def FutureWithMultiplier():
#! [futcontract_multiplier]
contract = Contract()
contract.symbol = "DAX"
contract.secType = "FUT"
contract.exchange = "DTB"
contract.currency = "EUR"
contract.lastTradeDateOrContractMonth = "201609"
contract.multiplier = "5"
#! [futcontract_multiplier]
return contract
""" Note the space in the symbol! """
@staticmethod
def WrongContract():
contract = Contract()
contract.symbol = " IJR "
contract.conId = 9579976
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
return contract
@staticmethod
def FuturesOnOptions():
#! [fopcontract]
contract = Contract()
contract.symbol = "SPX"
contract.secType = "FOP"
contract.exchange = "GLOBEX"
contract.currency = "USD"
contract.lastTradeDateOrContractMonth = "20180315"
contract.strike = 1025
contract.right = "C"
contract.multiplier = "250"
#! [fopcontract]
return contract
""" It is also possible to define contracts based on their ISIN (IBKR STK
sample). """
@staticmethod
def ByISIN():
contract = Contract()
contract.secIdType = "ISIN"
contract.secId = "US45841N1072"
contract.exchange = "SMART"
contract.currency = "USD"
contract.secType = "STK"
return contract
""" Or their conId (EUR.uSD sample).
Note: passing a contract containing the conId can cause problems if one of
the other provided attributes does not match 100% with what is in IB's
database. This is particularly important for contracts such as Bonds which
may change their description from one day to another.
If the conId is provided, it is best not to give too much information as
in the example below. """
@staticmethod
def ByConId():
contract = Contract()
contract.secType = "CASH"
contract.conId = 12087792
contract.exchange = "IDEALPRO"
return contract
""" Ambiguous contracts are great to use with reqContractDetails. This way
you can query the whole option chain for an underlying. Bear in mind that
there are pacing mechanisms in place which will delay any further responses
from the TWS to prevent abuse. """
@staticmethod
def OptionForQuery():
#! [optionforquery]
contract = Contract()
contract.symbol = "FISV"
contract.secType = "OPT"
contract.exchange = "SMART"
contract.currency = "USD"
#! [optionforquery]
return contract
@staticmethod
def OptionComboContract():
#! [bagoptcontract]
contract = Contract()
contract.symbol = "DBK"
contract.secType = "BAG"
contract.currency = "EUR"
contract.exchange = "DTB"
leg1 = ComboLeg()
leg1.conId = 197397509 #DBK JUN 15 2018 C
leg1.ratio = 1
leg1.action = "BUY"
leg1.exchange = "DTB"
leg2 = ComboLeg()
leg2.conId = 197397584 #DBK JUN 15 2018 P
leg2.ratio = 1
leg2.action = "SELL"
leg2.exchange = "DTB"
contract.comboLegs = []
contract.comboLegs.append(leg1)
contract.comboLegs.append(leg2)
#! [bagoptcontract]
return contract
""" STK Combo contract
Leg 1: 43645865 - IBKR's STK
Leg 2: 9408 - McDonald's STK """
@staticmethod
def StockComboContract():
#! [bagstkcontract]
contract = Contract()
contract.symbol = "IBKR,MCD"
contract.secType = "BAG"
contract.currency = "USD"
contract.exchange = "SMART"
leg1 = ComboLeg()
leg1.conId = 43645865#IBKR STK
leg1.ratio = 1
leg1.action = "BUY"
leg1.exchange = "SMART"
leg2 = ComboLeg()
leg2.conId = 9408#MCD STK
leg2.ratio = 1
leg2.action = "SELL"
leg2.exchange = "SMART"
contract.comboLegs = []
contract.comboLegs.append(leg1)
contract.comboLegs.append(leg2)
#! [bagstkcontract]
return contract
""" CBOE Volatility Index Future combo contract """
@staticmethod
def FutureComboContract():
#! [bagfutcontract]
contract = Contract()
contract.symbol = "VIX"
contract.secType = "BAG"
contract.currency = "USD"
contract.exchange = "CFE"
leg1 = ComboLeg()
leg1.conId = 256038899 # VIX FUT 201708
leg1.ratio = 1
leg1.action = "BUY"
leg1.exchange = "CFE"
leg2 = ComboLeg()
leg2.conId = 260564703 # VIX FUT 201709
leg2.ratio = 1
leg2.action = "SELL"
leg2.exchange = "CFE"
contract.comboLegs = []
contract.comboLegs.append(leg1)
contract.comboLegs.append(leg2)
#! [bagfutcontract]
return contract
@staticmethod
def SmartFutureComboContract():
#! [smartfuturespread]
contract = Contract()
contract.symbol = "WTI" # WTI,COIL spread. Symbol can be defined as first leg symbol ("WTI") or currency ("USD")
contract.secType = "BAG"
contract.currency = "USD"
contract.exchange = "SMART"
leg1 = ComboLeg()
leg1.conId = 55928698 # WTI future June 2017
leg1.ratio = 1
leg1.action = "BUY"
leg1.exchange = "IPE"
leg2 = ComboLeg()
leg2.conId = 55850663 # COIL future June 2017
leg2.ratio = 1
leg2.action = "SELL"
leg2.exchange = "IPE"
contract.comboLegs = []
contract.comboLegs.append(leg1)
contract.comboLegs.append(leg2)
#! [smartfuturespread]
return contract
@staticmethod
def InterCmdtyFuturesContract():
#! [intcmdfutcontract]
contract = Contract()
contract.symbol = "CL.BZ" #symbol is 'local symbol' of intercommodity spread.
contract.secType = "BAG"
contract.currency = "USD"
contract.exchange = "NYMEX"
leg1 = ComboLeg()
leg1.conId = 47207310 #CL Dec'16 @NYMEX
leg1.ratio = 1
leg1.action = "BUY"
leg1.exchange = "NYMEX"
leg2 = ComboLeg()
leg2.conId = 47195961 #BZ Dec'16 @NYMEX
leg2.ratio = 1
leg2.action = "SELL"
leg2.exchange = "NYMEX"
contract.comboLegs = []
contract.comboLegs.append(leg1)
contract.comboLegs.append(leg2)
#! [intcmdfutcontract]
return contract
@staticmethod
def NewsFeedForQuery():
#! [newsfeedforquery]
contract = Contract()
contract.secType = "NEWS"
contract.exchange = "BT" #Briefing Trader
#! [newsfeedforquery]
return contract
@staticmethod
def BTbroadtapeNewsFeed():
#! [newscontractbt]
contract = Contract()
contract.symbol = "BT:BT_ALL" #BroadTape All News
contract.secType = "NEWS"
contract.exchange = "BT" #Briefing Trader
#! [newscontractbt]
return contract
@staticmethod
def BZbroadtapeNewsFeed():
#! [newscontractbz]
contract = Contract()
contract.symbol = "BZ:BZ_ALL" #BroadTape All News
contract.secType = "NEWS"
contract.exchange = "BZ" #Benzinga Pro
#! [newscontractbz]
return contract
@staticmethod
def FLYbroadtapeNewsFeed():
#! [newscontractfly]
contract = Contract()
contract.symbol = "FLY:FLY_ALL" #BroadTape All News
contract.secType = "NEWS"
contract.exchange = "FLY" #Fly on the Wall
#! [newscontractfly]
return contract
@staticmethod
def MTbroadtapeNewsFeed():
#! [newscontractmt]
contract = Contract()
contract.symbol = "MT:MT_ALL" #BroadTape All News
contract.secType = "NEWS"
contract.exchange = "MT" #Midnight Trader
#! [newscontractmt]
return contract
@staticmethod
def ContFut():
#! [continuousfuturescontract]
contract = Contract()
contract.symbol = "ES"
contract.secType = "CONTFUT"
contract.exchange = "GLOBEX"
#! [continuousfuturescontract]
return contract
@staticmethod
def ContAndExpiringFut():
#! [contandexpiringfut]
contract = Contract()
contract.symbol = "ES"
contract.secType = "FUT+CONTFUT"
contract.exchange = "GLOBEX"
#! [contandexpiringfut]
return contract
@staticmethod
def JefferiesContract():
#! [jefferies_contract]
contract = Contract()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.exchange = "JEFFALGO"
contract.currency = "USD"
#! [jefferies_contract]
return contract
@staticmethod
def CSFBContract():
#! [csfb_contract]
contract = Contract()
contract.symbol = "IBKR"
contract.secType = "STK"
contract.exchange = "CSFBALGO"
contract.currency = "USD"
#! [csfb_contract]
return contract
def Test():
from ibapi.utils import ExerciseStaticMethods
ExerciseStaticMethods(ContractSamples)
if "__main__" == __name__:
Test()
"""
Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
import sys
from ibapi.object_implem import Object
class FaAllocationSamples(Object):
#! [faonegroup]
FaOneGroup = "".join(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<ListOfGroups>"
, "<Group>"
, "<name>Equal_Quantity</name>"
, "<ListOfAccts varName=\"list\">"
#Replace with your own accountIds
, "<String>DU119915</String>"
, "<String>DU119916</String>"
, "</ListOfAccts>"
, "<defaultMethod>EqualQuantity</defaultMethod>"
, "</Group>"
, "</ListOfGroups>"))
#! [faonegroup]
#! [fatwogroups]
FaTwoGroups = "".join(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
,"<ListOfGroups>"
, "<Group>"
, "<name>Equal_Quantity</name>"
, "<ListOfAccts varName=\"list\">"
#Replace with your own accountIds
, "<String>DU119915</String>"
, "<String>DU119916</String>"
, "</ListOfAccts>"
, "<defaultMethod>EqualQuantity</defaultMethod>"
, "</Group>"
, "<Group>"
, "<name>Pct_Change</name>"
, "<ListOfAccts varName=\"list\">"
#Replace with your own accountIds
, "<String>DU119915</String>"
, "<String>DU119916</String>"
, "</ListOfAccts>"
, "<defaultMethod>PctChange</defaultMethod>"
, "</Group>"
, "</ListOfGroups>"))
#! [fatwogroups]
#! [faoneprofile]
FaOneProfile = "".join(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<ListOfAllocationProfiles>"
, "<AllocationProfile>"
, "<name>Percent_60_40</name>"
, "<type>1</type>"
, "<ListOfAllocations varName=\"listOfAllocations\">"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119915</acct>"
, "<amount>60.0</amount>"
, "</Allocation>"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119916</acct>"
, "<amount>40.0</amount>"
, "</Allocation>"
, "</ListOfAllocations>"
, "</AllocationProfile>"
, "</ListOfAllocationProfiles>"))
#! [faoneprofile]
#! [fatwoprofiles]
FaTwoProfiles = "".join(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<ListOfAllocationProfiles>"
, "<AllocationProfile>"
, "<name>Percent_60_40</name>"
, "<type>1</type>"
, "<ListOfAllocations varName=\"listOfAllocations\">"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119915</acct>"
, "<amount>60.0</amount>"
, "</Allocation>"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119916</acct>"
, "<amount>40.0</amount>"
, "</Allocation>"
, "</ListOfAllocations>"
, "</AllocationProfile>"
, "<AllocationProfile>"
, "<name>Ratios_2_1</name>"
, "<type>1</type>"
, "<ListOfAllocations varName=\"listOfAllocations\">"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119915</acct>"
, "<amount>2.0</amount>"
, "</Allocation>"
, "<Allocation>"
#Replace with your own accountIds
, "<acct>DU119916</acct>"
, "<amount>1.0</amount>"
, "</Allocation>"
, "</ListOfAllocations>"
, "</AllocationProfile>"
, "</ListOfAllocationProfiles>"))
#! [fatwoprofiles]
def Test():
print(FaAllocationSamples.FaOneGroup)
print(FaAllocationSamples.FaTwoGroups)
print(FaAllocationSamples.FaOneProfile)
print(FaAllocationSamples.FaTwoProfiles)
if "__main__" == __name__:
Test()
"""
Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
import sys
import ibapi.order_condition
from ibapi.order import (OrderComboLeg, Order)
from ibapi.common import *
from ibapi.tag_value import TagValue
from ibapi import order_condition
from ibapi.order_condition import *
class OrderSamples:
""" <summary>
#/ An auction order is entered into the electronic trading system during the pre-market opening period for execution at the
#/ Calculated Opening Price (COP). If your order is not filled on the open, the order is re-submitted as a limit order with
#/ the limit price set to the COP or the best bid/ask after the market opens.
#/ Products: FUT, STK
</summary>"""
@staticmethod
def AtAuction(action:str, quantity:float, price:float):
#! [auction]
order = Order()
order.action = action
order.tif = "AUC"
order.orderType = "MTL"
order.totalQuantity = quantity
order.lmtPrice = price
#! [auction]
return order
""" <summary>
#/ A Discretionary order is a limit order submitted with a hidden, specified 'discretionary' amount off the limit price which
#/ may be used to increase the price range over which the limit order is eligible to execute. The market sees only the limit price.
#/ Products: STK
</summary>"""
@staticmethod
def Discretionary(action:str, quantity:float, price:float, discretionaryAmount:float):
#! [discretionary]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = price
order.discretionaryAmt = discretionaryAmount
#! [discretionary]
return order
""" <summary>
#/ A Market order is an order to buy or sell at the market bid or offer price. A market order may increase the likelihood of a fill
#/ and the speed of execution, but unlike the Limit order a Market order provides no price protection and may fill at a price far
#/ lower/higher than the current displayed bid/ask.
#/ Products: BOND, CFD, EFP, CASH, FUND, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def MarketOrder(action:str, quantity:float):
#! [market]
order = Order()
order.action = action
order.orderType = "MKT"
order.totalQuantity = quantity
#! [market]
return order
""" <summary>
#/ A Market if Touched (MIT) is an order to buy (or sell) a contract below (or above) the market. Its purpose is to take advantage
#/ of sudden or unexpected changes in share or other prices and provides investors with a trigger price to set an order in motion.
#/ Investors may be waiting for excessive strength (or weakness) to cease, which might be represented by a specific price point.
#/ MIT orders can be used to determine whether or not to enter the market once a specific price level has been achieved. This order
#/ is held in the system until the trigger price is touched, and is then submitted as a market order. An MIT order is similar to a
#/ stop order, except that an MIT sell order is placed above the current market price, and a stop sell order is placed below
#/ Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def MarketIfTouched(action:str, quantity:float, price:float):
#! [market_if_touched]
order = Order()
order.action = action
order.orderType = "MIT"
order.totalQuantity = quantity
order.auxPrice = price
#! [market_if_touched]
return order
""" <summary>
#/ A Market-on-Close (MOC) order is a market order that is submitted to execute as close to the closing price as possible.
#/ Products: CFD, FUT, STK, WAR
</summary>"""
@staticmethod
def MarketOnClose(action:str, quantity:float):
#! [market_on_close]
order = Order()
order.action = action
order.orderType = "MOC"
order.totalQuantity = quantity
#! [market_on_close]
return order
""" <summary>
#/ A Market-on-Open (MOO) order combines a market order with the OPG time in force to create an order that is automatically
#/ submitted at the market's open and fills at the market price.
#/ Products: CFD, STK, OPT, WAR
</summary>"""
@staticmethod
def MarketOnOpen(action:str, quantity:float):
#! [market_on_open]
order = Order()
order.action = action
order.orderType = "MKT"
order.totalQuantity = quantity
order.tif = "OPG"
#! [market_on_open]
return order
""" <summary>
#/ ISE MidpoMatch:int (MPM) orders always execute at the midpoof:the:int NBBO. You can submit market and limit orders direct-routed
#/ to ISE for MPM execution. Market orders execute at the midpowhenever:an:int eligible contra-order is available. Limit orders
#/ execute only when the midpoprice:is:int better than the limit price. Standard MPM orders are completely anonymous.
#/ Products: STK
</summary>"""
@staticmethod
def MidpointMatch(action:str, quantity:float):
#! [midpoint_match]
order = Order()
order.action = action
order.orderType = "MKT"
order.totalQuantity = quantity
#! [midpoint_match]
return order
""" <summary>
#/ A pegged-to-market order is designed to maintain a purchase price relative to the national best offer (NBO) or a sale price
#/ relative to the national best bid (NBB). Depending on the width of the quote, this order may be passive or aggressive.
#/ The trader creates the order by entering a limit price which defines the worst limit price that they are willing to accept.
#/ Next, the trader enters an offset amount which computes the active limit price as follows:
#/ Sell order price = Bid price + offset amount
#/ Buy order price = Ask price - offset amount
#/ Products: STK
</summary>"""
@staticmethod
def PeggedToMarket(action:str, quantity:float, marketOffset:float):
#! [pegged_market]
order = Order()
order.action = action
order.orderType = "PEG MKT"
order.totalQuantity = quantity
order.auxPrice = marketOffset#Offset price
#! [pegged_market]
return order
""" <summary>
#/ A Pegged to Stock order continually adjusts the option order price by the product of a signed user-define delta and the change of
#/ the option's underlying stock price. The delta is entered as an absolute and assumed to be positive for calls and negative for puts.
#/ A buy or sell call order price is determined by adding the delta times a change in an underlying stock price to a specified starting
#/ price for the call. To determine the change in price, the stock reference price is subtracted from the current NBBO midpoint.
#/ The Stock Reference Price can be defined by the user, or defaults to the NBBO midpoat:the:int time of the order if no reference price
#/ is entered. You may also enter a high/low stock price range which cancels the order when reached. The delta times the change in stock
#/ price will be rounded to the nearest penny in favor of the order.
#/ Products: OPT
</summary>"""
@staticmethod
def PeggedToStock(action:str, quantity:float, delta:float, stockReferencePrice:float, startingPrice:float):
#! [pegged_stock]
order = Order()
order.action = action
order.orderType = "PEG STK"
order.totalQuantity = quantity
order.delta = delta
order.lmtPrice = stockReferencePrice
order.startingPrice = startingPrice
#! [pegged_stock]
return order
""" <summary>
#/ Relative (a.k.a. Pegged-to-Primary) orders provide a means for traders to seek a more aggressive price than the National Best Bid
#/ and Offer (NBBO). By acting as liquidity providers, and placing more aggressive bids and offers than the current best bids and offers,
#/ traders increase their odds of filling their order. Quotes are automatically adjusted as the markets move, to remain aggressive.
#/ For a buy order, your bid is pegged to the NBB by a more aggressive offset, and if the NBB moves up, your bid will also move up.
#/ If the NBB moves down, there will be no adjustment because your bid will become even more aggressive and execute. For sales, your
#/ offer is pegged to the NBO by a more aggressive offset, and if the NBO moves down, your offer will also move down. If the NBO moves up,
#/ there will be no adjustment because your offer will become more aggressive and execute. In addition to the offset, you can define an
#/ absolute cap, which works like a limit price, and will prevent your order from being executed above or below a specified level.
#/ Stocks, Options and Futures - not available on paper trading
#/ Products: CFD, STK, OPT, FUT
</summary>"""
@staticmethod
def RelativePeggedToPrimary(action:str, quantity:float, priceCap:float,
offsetAmount:float):
#! [relative_pegged_primary]
order = Order()
order.action = action
order.orderType = "REL"
order.totalQuantity = quantity
order.lmtPrice = priceCap
order.auxPrice = offsetAmount
#! [relative_pegged_primary]
return order
""" <summary>
#/ Sweep-to-fill orders are useful when a trader values speed of execution over price. A sweep-to-fill order identifies the best price
#/ and the exact quantity offered/available at that price, and transmits the corresponding portion of your order for immediate execution.
#/ Simultaneously it identifies the next best price and quantity offered/available, and submits the matching quantity of your order for
#/ immediate execution.
#/ Products: CFD, STK, WAR
</summary>"""
@staticmethod
def SweepToFill(action:str, quantity:float, price:float):
#! [sweep_to_fill]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = price
order.sweepToFill = True
#! [sweep_to_fill]
return order
""" <summary>
#/ For option orders routed to the Boston Options Exchange (BOX) you may elect to participate in the BOX's price improvement auction in
#/ pennies. All BOX-directed price improvement orders are immediately sent from Interactive Brokers to the BOX order book, and when the
#/ terms allow, IB will evaluate it for inclusion in a price improvement auction based on price and volume priority. In the auction, your
#/ order will have priority over broker-dealer price improvement orders at the same price.
#/ An Auction Limit order at a specified price. Use of a limit order ensures that you will not receive an execution at a price less favorable
#/ than the limit price. Enter limit orders in penny increments with your auction improvement amount computed as the difference between your
#/ limit order price and the nearest listed increment.
#/ Products: OPT
#/ Supported Exchanges: BOX
</summary>"""
@staticmethod
def AuctionLimit(action:str, quantity:float, price:float,
auctionStrategy:int):
#! [auction_limit]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = price
order.auctionStrategy = auctionStrategy
#! [auction_limit]
return order
""" <summary>
#/ For option orders routed to the Boston Options Exchange (BOX) you may elect to participate in the BOX's price improvement auction in pennies.
#/ All BOX-directed price improvement orders are immediately sent from Interactive Brokers to the BOX order book, and when the terms allow,
#/ IB will evaluate it for inclusion in a price improvement auction based on price and volume priority. In the auction, your order will have
#/ priority over broker-dealer price improvement orders at the same price.
#/ An Auction Pegged to Stock order adjusts the order price by the product of a signed delta (which is entered as an absolute and assumed to be
#/ positive for calls, negative for puts) and the change of the option's underlying stock price. A buy or sell call order price is determined
#/ by adding the delta times a change in an underlying stock price change to a specified starting price for the call. To determine the change
#/ in price, a stock reference price (NBBO midpoat:the:int time of the order is assumed if no reference price is entered) is subtracted from
#/ the current NBBO midpoint. A stock range may also be entered that cancels an order when reached. The delta times the change in stock price
#/ will be rounded to the nearest penny in favor of the order and will be used as your auction improvement amount.
#/ Products: OPT
#/ Supported Exchanges: BOX
</summary>"""
@staticmethod
def AuctionPeggedToStock(action:str, quantity:float, startingPrice:float,
delta:float):
#! [auction_pegged_stock]
order = Order()
order.action = action
order.orderType = "PEG STK"
order.totalQuantity = quantity
order.delta = delta
order.startingPrice = startingPrice
#! [auction_pegged_stock]
return order
""" <summary>
#/ For option orders routed to the Boston Options Exchange (BOX) you may elect to participate in the BOX's price improvement auction in pennies.
#/ All BOX-directed price improvement orders are immediately sent from Interactive Brokers to the BOX order book, and when the terms allow,
#/ IB will evaluate it for inclusion in a price improvement auction based on price and volume priority. In the auction, your order will have
#/ priority over broker-dealer price improvement orders at the same price.
#/ An Auction Relative order that adjusts the order price by the product of a signed delta (which is entered as an absolute and assumed to be
#/ positive for calls, negative for puts) and the change of the option's underlying stock price. A buy or sell call order price is determined
#/ by adding the delta times a change in an underlying stock price change to a specified starting price for the call. To determine the change
#/ in price, a stock reference price (NBBO midpoat:the:int time of the order is assumed if no reference price is entered) is subtracted from
#/ the current NBBO midpoint. A stock range may also be entered that cancels an order when reached. The delta times the change in stock price
#/ will be rounded to the nearest penny in favor of the order and will be used as your auction improvement amount.
#/ Products: OPT
#/ Supported Exchanges: BOX
</summary>"""
@staticmethod
def AuctionRelative(action:str, quantity:float, offset:float):
#! [auction_relative]
order = Order()
order.action = action
order.orderType = "REL"
order.totalQuantity = quantity
order.auxPrice = offset
#! [auction_relative]
return order
""" <summary>
#/ The Block attribute is used for large volume option orders on ISE that consist of at least 50 contracts. To execute large-volume
#/ orders over time without moving the market, use the Accumulate/Distribute algorithm.
#/ Products: OPT
</summary>"""
@staticmethod
def Block(action:str, quantity:float, price:float):
# ! [block]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity#Large volumes!
order.lmtPrice = price
order.blockOrder = True
# ! [block]
return order
""" <summary>
#/ A Box Top order executes as a market order at the current best price. If the order is only partially filled, the remainder is submitted as
#/ a limit order with the limit price equal to the price at which the filled portion of the order executed.
#/ Products: OPT
#/ Supported Exchanges: BOX
</summary>"""
@staticmethod
def BoxTop(action:str, quantity:float):
# ! [boxtop]
order = Order()
order.action = action
order.orderType = "BOX TOP"
order.totalQuantity = quantity
# ! [boxtop]
return order
""" <summary>
#/ A Limit order is an order to buy or sell at a specified price or better. The Limit order ensures that if the order fills,
#/ it will not fill at a price less favorable than your limit price, but it does not guarantee a fill.
#/ Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def LimitOrder(action:str, quantity:float, limitPrice:float):
# ! [limitorder]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
# ! [limitorder]
return order
""" <summary>
#/ Forex orders can be placed in demonination of second currency in pair using cashQty field
#/ Requires TWS or IBG 963+
#/ https://www.interactivebrokers.com/en/index.php?f=23876#963-02
</summary>"""
@staticmethod
def LimitOrderWithCashQty(action:str, quantity:float, limitPrice:float, cashQty:float):
# ! [limitorderwithcashqty]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
order.cashQty = cashQty
# ! [limitorderwithcashqty]
return order
""" <summary>
#/ A Limit if Touched is an order to buy (or sell) a contract at a specified price or better, below (or above) the market. This order is
#/ held in the system until the trigger price is touched. An LIT order is similar to a stop limit order, except that an LIT sell order is
#/ placed above the current market price, and a stop limit sell order is placed below.
#/ Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def LimitIfTouched(action:str, quantity:float, limitPrice:float,
triggerPrice:float):
# ! [limitiftouched]
order = Order()
order.action = action
order.orderType = "LIT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
order.auxPrice = triggerPrice
# ! [limitiftouched]
return order
""" <summary>
#/ A Limit-on-close (LOC) order will be submitted at the close and will execute if the closing price is at or better than the submitted
#/ limit price.
#/ Products: CFD, FUT, STK, WAR
</summary>"""
@staticmethod
def LimitOnClose(action:str, quantity:float, limitPrice:float):
# ! [limitonclose]
order = Order()
order.action = action
order.orderType = "LOC"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
# ! [limitonclose]
return order
""" <summary>
#/ A Limit-on-Open (LOO) order combines a limit order with the OPG time in force to create an order that is submitted at the market's open,
#/ and that will only execute at the specified limit price or better. Orders are filled in accordance with specific exchange rules.
#/ Products: CFD, STK, OPT, WAR
</summary>"""
@staticmethod
def LimitOnOpen(action:str, quantity:float, limitPrice:float):
# ! [limitonopen]
order = Order()
order.action = action
order.tif = "OPG"
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
# ! [limitonopen]
return order
""" <summary>
#/ Passive Relative orders provide a means for traders to seek a less aggressive price than the National Best Bid and Offer (NBBO) while
#/ keeping the order pegged to the best bid (for a buy) or ask (for a sell). The order price is automatically adjusted as the markets move
#/ to keep the order less aggressive. For a buy order, your order price is pegged to the NBB by a less aggressive offset, and if the NBB
#/ moves up, your bid will also move up. If the NBB moves down, there will be no adjustment because your bid will become aggressive and execute.
#/ For a sell order, your price is pegged to the NBO by a less aggressive offset, and if the NBO moves down, your offer will also move down.
#/ If the NBO moves up, there will be no adjustment because your offer will become aggressive and execute. In addition to the offset, you can
#/ define an absolute cap, which works like a limit price, and will prevent your order from being executed above or below a specified level.
#/ The Passive Relative order is similar to the Relative/Pegged-to-Primary order, except that the Passive relative subtracts the offset from
#/ the bid and the Relative adds the offset to the bid.
#/ Products: STK, WAR
</summary>"""
@staticmethod
def PassiveRelative(action:str, quantity:float, offset:float):
# ! [passive_relative]
order = Order()
order.action = action
order.orderType = "PASSV REL"
order.totalQuantity = quantity
order.auxPrice = offset
# ! [passive_relative]
return order
""" <summary>
#/ A pegged-to-midpoorder:provides:int a means for traders to seek a price at the midpoof:the:int National Best Bid and Offer (NBBO).
#/ The price automatically adjusts to peg the midpoas:the:int markets move, to remain aggressive. For a buy order, your bid is pegged to
#/ the NBBO midpoand:the:int order price adjusts automatically to continue to peg the midpoif:the:int market moves. The price only adjusts
#/ to be more aggressive. If the market moves in the opposite direction, the order will execute.
#/ Products: STK
</summary>"""
@staticmethod
def PeggedToMidpoint(action:str, quantity:float, offset:float, limitPrice:float):
# ! [pegged_midpoint]
order = Order()
order.action = action
order.orderType = "PEG MID"
order.totalQuantity = quantity
order.auxPrice = offset
order.lmtPrice = limitPrice
# ! [pegged_midpoint]
return order
""" <summary>
#/ Bracket orders are designed to help limit your loss and lock in a profit by "bracketing" an order with two opposite-side orders.
#/ A BUY order is bracketed by a high-side sell limit order and a low-side sell stop order. A SELL order is bracketed by a high-side buy
#/ stop order and a low side buy limit order.
#/ Products: CFD, BAG, FOP, CASH, FUT, OPT, STK, WAR
</summary>"""
#! [bracket]
@staticmethod
def BracketOrder(parentOrderId:int, action:str, quantity:float,
limitPrice:float, takeProfitLimitPrice:float,
stopLossPrice:float):
#This will be our main or "parent" order
parent = Order()
parent.orderId = parentOrderId
parent.action = action
parent.orderType = "LMT"
parent.totalQuantity = quantity
parent.lmtPrice = limitPrice
#The parent and children orders will need this attribute set to False to prevent accidental executions.
#The LAST CHILD will have it set to True,
parent.transmit = False
takeProfit = Order()
takeProfit.orderId = parent.orderId + 1
takeProfit.action = "SELL" if action == "BUY" else "BUY"
takeProfit.orderType = "LMT"
takeProfit.totalQuantity = quantity
takeProfit.lmtPrice = takeProfitLimitPrice
takeProfit.parentId = parentOrderId
takeProfit.transmit = False
stopLoss = Order()
stopLoss.orderId = parent.orderId + 2
stopLoss.action = "SELL" if action == "BUY" else "BUY"
stopLoss.orderType = "STP"
#Stop trigger price
stopLoss.auxPrice = stopLossPrice
stopLoss.totalQuantity = quantity
stopLoss.parentId = parentOrderId
#In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to True
#to activate all its predecessors
stopLoss.transmit = True
bracketOrder = [parent, takeProfit, stopLoss]
return bracketOrder
#! [bracket]
""" <summary>
#/ Products:CFD, FUT, FOP, OPT, STK, WAR
#/ A Market-to-Limit (MTL) order is submitted as a market order to execute at the current best market price. If the order is only
#/ partially filled, the remainder of the order is canceled and re-submitted as a limit order with the limit price equal to the price
#/ at which the filled portion of the order executed.
</summary>"""
@staticmethod
def MarketToLimit(action:str, quantity:float):
# ! [markettolimit]
order = Order()
order.action = action
order.orderType = "MTL"
order.totalQuantity = quantity
# ! [markettolimit]
return order
""" <summary>
#/ This order type is useful for futures traders using Globex. A Market with Protection order is a market order that will be cancelled and
#/ resubmitted as a limit order if the entire order does not immediately execute at the market price. The limit price is set by Globex to be
#/ close to the current market price, slightly higher for a sell order and lower for a buy order.
#/ Products: FUT, FOP
</summary>"""
@staticmethod
def MarketWithProtection(action:str, quantity:float):
# ! [marketwithprotection]
order = Order()
order.action = action
order.orderType = "MKT PRT"
order.totalQuantity = quantity
# ! [marketwithprotection]
return order
""" <summary>
#/ A Stop order is an instruction to submit a buy or sell market order if and when the user-specified stop trigger price is attained or
#/ penetrated. A Stop order is not guaranteed a specific execution price and may execute significantly away from its stop price. A Sell
#/ Stop order is always placed below the current market price and is typically used to limit a loss or protect a profit on a long stock
#/ position. A Buy Stop order is always placed above the current market price. It is typically used to limit a loss or help protect a
#/ profit on a short sale.
#/ Products: CFD, BAG, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def Stop(action:str, quantity:float, stopPrice:float):
# ! [stop]
order = Order()
order.action = action
order.orderType = "STP"
order.auxPrice = stopPrice
order.totalQuantity = quantity
# ! [stop]
return order
""" <summary>
#/ A Stop-Limit order is an instruction to submit a buy or sell limit order when the user-specified stop trigger price is attained or
#/ penetrated. The order has two basic components: the stop price and the limit price. When a trade has occurred at or through the stop
#/ price, the order becomes executable and enters the market as a limit order, which is an order to buy or sell at a specified price or better.
#/ Products: CFD, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def StopLimit(action:str, quantity:float, limitPrice:float, stopPrice:float):
# ! [stoplimit]
order = Order()
order.action = action
order.orderType = "STP LMT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
order.auxPrice = stopPrice
# ! [stoplimit]
return order
""" <summary>
#/ A Stop with Protection order combines the functionality of a stop limit order with a market with protection order. The order is set
#/ to trigger at a specified stop price. When the stop price is penetrated, the order is triggered as a market with protection order,
#/ which means that it will fill within a specified protected price range equal to the trigger price +/- the exchange-defined protection
#/ porange:int. Any portion of the order that does not fill within this protected range is submitted as a limit order at the exchange-defined
#/ trigger price +/- the protection points.
#/ Products: FUT
</summary>"""
@staticmethod
def StopWithProtection(action:str, quantity:float, stopPrice:float):
# ! [stopwithprotection]
order = Order()
order.totalQuantity = quantity
order.action = action
order.orderType = "STP PRT"
order.auxPrice = stopPrice
# ! [stopwithprotection]
return order
""" <summary>
#/ A sell trailing stop order sets the stop price at a fixed amount below the market price with an attached "trailing" amount. As the
#/ market price rises, the stop price rises by the trail amount, but if the stock price falls, the stop loss price doesn't change,
#/ and a market order is submitted when the stop price is hit. This technique is designed to allow an investor to specify a limit on the
#/ maximum possible loss, without setting a limit on the maximum possible gain. "Buy" trailing stop orders are the mirror image of sell
#/ trailing stop orders, and are most appropriate for use in falling markets.
#/ Products: CFD, CASH, FOP, FUT, OPT, STK, WAR
</summary>"""
@staticmethod
def TrailingStop(action:str, quantity:float, trailingPercent:float,
trailStopPrice:float):
# ! [trailingstop]
order = Order()
order.action = action
order.orderType = "TRAIL"
order.totalQuantity = quantity
order.trailingPercent = trailingPercent
order.trailStopPrice = trailStopPrice
# ! [trailingstop]
return order
""" <summary>
#/ A trailing stop limit order is designed to allow an investor to specify a limit on the maximum possible loss, without setting a limit
#/ on the maximum possible gain. A SELL trailing stop limit moves with the market price, and continually recalculates the stop trigger
#/ price at a fixed amount below the market price, based on the user-defined "trailing" amount. The limit order price is also continually
#/ recalculated based on the limit offset. As the market price rises, both the stop price and the limit price rise by the trail amount and
#/ limit offset respectively, but if the stock price falls, the stop price remains unchanged, and when the stop price is hit a limit order
#/ is submitted at the last calculated limit price. A "Buy" trailing stop limit order is the mirror image of a sell trailing stop limit,
#/ and is generally used in falling markets.
#/ Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR
</summary>"""
@staticmethod
def TrailingStopLimit(action:str, quantity:float, lmtPriceOffset:float,
trailingAmount:float, trailStopPrice:float):
# ! [trailingstoplimit]
order = Order()
order.action = action
order.orderType = "TRAIL LIMIT"
order.totalQuantity = quantity
order.trailStopPrice = trailStopPrice
order.lmtPriceOffset = lmtPriceOffset
order.auxPrice = trailingAmount
# ! [trailingstoplimit]
return order
""" <summary>
#/ Create combination orders that include options, stock and futures legs (stock legs can be included if the order is routed
#/ through SmartRouting). Although a combination/spread order is constructed of separate legs, it is executed as a single transaction
#/ if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure
#/ best execution.
#/ Products: OPT, STK, FUT
</summary>"""
@staticmethod
def ComboLimitOrder(action:str, quantity:float, limitPrice:float,
nonGuaranteed:bool):
# ! [combolimit]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = limitPrice
if nonGuaranteed:
order.smartComboRoutingParams = []
order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1"))
# ! [combolimit]
return order
""" <summary>
#/ Create combination orders that include options, stock and futures legs (stock legs can be included if the order is routed
#/ through SmartRouting). Although a combination/spread order is constructed of separate legs, it is executed as a single transaction
#/ if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure
#/ best execution.
#/ Products: OPT, STK, FUT
</summary>"""
@staticmethod
def ComboMarketOrder(action:str, quantity:float, nonGuaranteed:bool):
# ! [combomarket]
order = Order()
order.action = action
order.orderType = "MKT"
order.totalQuantity = quantity
if nonGuaranteed:
order.smartComboRoutingParams = []
order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1"))
# ! [combomarket]
return order
""" <summary>
#/ Create combination orders that include options, stock and futures legs (stock legs can be included if the order is routed
#/ through SmartRouting). Although a combination/spread order is constructed of separate legs, it is executed as a single transaction
#/ if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure
#/ best execution.
#/ Products: OPT, STK, FUT
</summary>"""
@staticmethod
def LimitOrderForComboWithLegPrices(action:str, quantity:float,
legPrices:list, nonGuaranteed:bool):
# ! [limitordercombolegprices]
order = Order()
order.action = action
order.orderType = "LMT"
order.totalQuantity = quantity
order.orderComboLegs = []
for price in legPrices:
comboLeg = OrderComboLeg()
comboLeg.price = price
order.orderComboLegs.append(comboLeg)
if nonGuaranteed:
order.smartComboRoutingParams = []
order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1"))
# ! [limitordercombolegprices]
return order
""" <summary>
#/ Create combination orders that include options, stock and futures legs (stock legs can be included if the order is routed
#/ through SmartRouting). Although a combination/spread order is constructed of separate legs, it is executed as a single transaction
#/ if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure
#/ best execution.
#/ Products: OPT, STK, FUT
</summary>"""
@staticmethod
def RelativeLimitCombo(action:str, quantity:float, limitPrice:float,
nonGuaranteed:bool):
# ! [relativelimitcombo]
order = Order()
order.action = action
order.totalQuantity = quantity
order.orderType = "REL + LMT"
order.lmtPrice = limitPrice
if nonGuaranteed:
order.smartComboRoutingParams = []
order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1"))
# ! [relativelimitcombo]
return order
""" <summary>
#/ Create combination orders that include options, stock and futures legs (stock legs can be included if the order is routed
#/ through SmartRouting). Although a combination/spread order is constructed of separate legs, it is executed as a single transaction
#/ if it is routed directly to an exchange. For combination orders that are SmartRouted, each leg may be executed separately to ensure
#/ best execution.
#/ Products: OPT, STK, FUT
</summary>"""
@staticmethod
def RelativeMarketCombo(action:str, quantity:float, nonGuaranteed:bool):
# ! [relativemarketcombo]
order = Order()
order.action = action
order.totalQuantity = quantity
order.orderType = "REL + MKT"
if nonGuaranteed:
order.smartComboRoutingParams = []
order.smartComboRoutingParams.append(TagValue("NonGuaranteed", "1"))
# ! [relativemarketcombo]
return order
""" <summary>
#/ One-Cancels All (OCA) order type allows an investor to place multiple and possibly unrelated orders assigned to a group. The aim is
#/ to complete just one of the orders, which in turn will cause TWS to cancel the remaining orders. The investor may submit several
#/ orders aimed at taking advantage of the most desirable price within the group. Completion of one piece of the group order causes
#/ cancellation of the remaining group orders while partial completion causes the group to rebalance. An investor might desire to sell
#/ 1000 shares of only ONE of three positions held above prevailing market prices. The OCA order group allows the investor to enter prices
#/ at specified target levels and if one is completed, the other two will automatically cancel. Alternatively, an investor may wish to take
#/ a LONG position in eMini S&P stock index futures in a falling market or else SELL US treasury futures at a more favorable price.
#/ Grouping the two orders using an OCA order type offers the investor two chance to enter a similar position, while only running the risk
#/ of taking on a single position.
#/ Products: BOND, CASH, FUT, FOP, STK, OPT, WAR
</summary>"""
# ! [oca]
@staticmethod
def OneCancelsAll(ocaGroup:str, ocaOrders:ListOfOrder, ocaType:int):
for o in ocaOrders:
o.ocaGroup = ocaGroup
o.ocaType = ocaType
return ocaOrders
# ! [oca]
""" <summary>
#/ Specific to US options, investors are able to create and enter Volatility-type orders for options and combinations rather than price orders.
#/ Option traders may wish to trade and position for movements in the price of the option determined by its implied volatility. Because
#/ implied volatility is a key determinant of the premium on an option, traders position in specific contract months in an effort to take
#/ advantage of perceived changes in implied volatility arising before, during or after earnings or when company specific or broad market
#/ volatility is predicted to change. In order to create a Volatility order, clients must first create a Volatility Trader page from the
#/ Trading Tools menu and as they enter option contracts, premiums will display in percentage terms rather than premium. The buy/sell process
#/ is the same as for regular orders priced in premium terms except that the client can limit the volatility level they are willing to pay or
#/ receive.
#/ Products: FOP, OPT
</summary>"""
@staticmethod
def Volatility(action:str, quantity:float, volatilityPercent:float,
volatilityType:int):
# ! [volatility]
order = Order()
order.action = action
order.orderType = "VOL"
order.totalQuantity = quantity
order.volatility = volatilityPercent#Expressed in percentage (40%)
order.volatilityType = volatilityType# 1=daily, 2=annual
# ! [volatility]
return order
#! [fhedge]
@staticmethod
def MarketFHedge(parentOrderId:int, action:str):
#FX Hedge orders can only have a quantity of 0
order = OrderSamples.MarketOrder(action, 0)
order.parentId = parentOrderId
order.hedgeType = "F"
return order
#! [fhedge]
@staticmethod
def PeggedToBenchmark(action:str, quantity:float, startingPrice:float,
peggedChangeAmountDecrease:bool,
peggedChangeAmount:float,
referenceChangeAmount:float, referenceConId:int,
referenceExchange:str, stockReferencePrice:float,
referenceContractLowerRange:float,
referenceContractUpperRange:float):
#! [pegged_benchmark]
order = Order()
order.orderType = "PEG BENCH"
#BUY or SELL
order.action = action
order.totalQuantity = quantity
#Beginning with price...
order.startingPrice = startingPrice
#increase/decrease price..
order.isPeggedChangeAmountDecrease = peggedChangeAmountDecrease
#by... (and likewise for price moving in opposite direction)
order.peggedChangeAmount = peggedChangeAmount
#whenever there is a price change of...
order.referenceChangeAmount = referenceChangeAmount
#in the reference contract...
order.referenceContractId = referenceConId
#being traded at...
order.referenceExchange = referenceExchange
#starting reference price is...
order.stockRefPrice = stockReferencePrice
#Keep order active as long as reference contract trades between...
order.stockRangeLower = referenceContractLowerRange
#and...
order.stockRangeUpper = referenceContractUpperRange
#! [pegged_benchmark]
return order
@staticmethod
def AttachAdjustableToStop(parent:Order , attachedOrderStopPrice:float,
triggerPrice:float, adjustStopPrice:float):
#! [adjustable_stop]
# Attached order is a conventional STP order in opposite direction
order = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
parent.totalQuantity, attachedOrderStopPrice)
order.parentId = parent.orderId
#When trigger price is penetrated
order.triggerPrice = triggerPrice
#The parent order will be turned into a STP order
order.adjustedOrderType = "STP"
#With the given STP price
order.adjustedStopPrice = adjustStopPrice
#! [adjustable_stop]
return order
@staticmethod
def AttachAdjustableToStopLimit(parent:Order, attachedOrderStopPrice:float,
triggerPrice:float, adjustedStopPrice:float,
adjustedStopLimitPrice:float):
#! [adjustable_stop_limit]
#Attached order is a conventional STP order
order = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
parent.totalQuantity, attachedOrderStopPrice)
order.parentId = parent.orderId
#When trigger price is penetrated
order.triggerPrice = triggerPrice
#The parent order will be turned into a STP LMT order
order.adjustedOrderType = "STP LMT"
#With the given stop price
order.adjustedStopPrice = adjustedStopPrice
#And the given limit price
order.adjustedStopLimitPrice = adjustedStopLimitPrice
#! [adjustable_stop_limit]
return order
@staticmethod
def AttachAdjustableToTrail(parent:Order, attachedOrderStopPrice:float,
triggerPrice:float, adjustedStopPrice:float,
adjustedTrailAmount:float, trailUnit:int):
#! [adjustable_trail]
#Attached order is a conventional STP order
order = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
parent.totalQuantity, attachedOrderStopPrice)
order.parentId = parent.orderId
#When trigger price is penetrated
order.triggerPrice = triggerPrice
#The parent order will be turned into a TRAIL order
order.adjustedOrderType = "TRAIL"
#With a stop price of...
order.adjustedStopPrice = adjustedStopPrice
#traling by and amount (0) or a percent (1)...
order.adjustableTrailingUnit = trailUnit
#of...
order.adjustedTrailingAmount = adjustedTrailAmount
#! [adjustable_trail]
return order
@staticmethod
def PriceCondition(triggerMethod:int, conId:int, exchange:str, price:float,
isMore:bool, isConjunction:bool):
#! [price_condition]
#Conditions have to be created via the OrderCondition.create
priceCondition = order_condition.Create(OrderCondition.Price)
#When this contract...
priceCondition.conId = conId
#traded on this exchange
priceCondition.exchange = exchange
#has a price above/below
priceCondition.isMore = isMore
priceCondition.triggerMethod = triggerMethod
#this quantity
priceCondition.price = price
#AND | OR next condition (will be ignored if no more conditions are added)
priceCondition.isConjunctionConnection = isConjunction
#! [price_condition]
return priceCondition
@staticmethod
def ExecutionCondition(symbol:str, secType:str, exchange:str,
isConjunction:bool):
#! [execution_condition]
execCondition = order_condition.Create(OrderCondition.Execution)
#When an execution on symbol
execCondition.symbol = symbol
#at exchange
execCondition.exchange = exchange
#for this secType
execCondition.secType = secType
#AND | OR next condition (will be ignored if no more conditions are added)
execCondition.isConjunctionConnection = isConjunction
#! [execution_condition]
return execCondition
@staticmethod
def MarginCondition(percent:int, isMore:bool, isConjunction:bool):
#! [margin_condition]
marginCondition = order_condition.Create(OrderCondition.Margin)
#If margin is above/below
marginCondition.isMore = isMore
#given percent
marginCondition.percent = percent
#AND | OR next condition (will be ignored if no more conditions are added)
marginCondition.isConjunctionConnection = isConjunction
#! [margin_condition]
return marginCondition
@staticmethod
def PercentageChangeCondition(pctChange:float, conId:int, exchange:str,
isMore:bool, isConjunction:bool):
#! [percentage_condition]
pctChangeCondition = order_condition.Create(OrderCondition.PercentChange)
#If there is a price percent change measured against last close price above or below...
pctChangeCondition.isMore = isMore
#this amount...
pctChangeCondition.changePercent = pctChange
#on this contract
pctChangeCondition.conId = conId
#when traded on this exchange...
pctChangeCondition.exchange = exchange
#AND | OR next condition (will be ignored if no more conditions are added)
pctChangeCondition.isConjunctionConnection = isConjunction
#! [percentage_condition]
return pctChangeCondition
@staticmethod
def TimeCondition(time:str, isMore:bool, isConjunction:bool):
#! [time_condition]
timeCondition = order_condition.Create(OrderCondition.Time)
#Before or after...
timeCondition.isMore = isMore
#this time..
timeCondition.time = time
#AND | OR next condition (will be ignored if no more conditions are added)
timeCondition.isConjunctionConnection = isConjunction
#! [time_condition]
return timeCondition
@staticmethod
def VolumeCondition(conId:int, exchange:str, isMore:bool, volume:int,
isConjunction:bool):
#! [volume_condition]
volCond = order_condition.Create(OrderCondition.Volume)
#Whenever contract...
volCond.conId = conId
#When traded at
volCond.exchange = exchange
#reaches a volume higher/lower
volCond.isMore = isMore
#than this...
volCond.volume = volume
#AND | OR next condition (will be ignored if no more conditions are added)
volCond.isConjunctionConnection = isConjunction
#! [volume_condition]
return volCond
def Test():
os = OrderSamples()
if "__main__" == __name__:
Test()
"""
Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
import sys
import argparse
import datetime
import collections
import inspect
import logging
import time
import os.path
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper
# types
from ibapi.common import *
from ibapi.order_condition import *
from ibapi.contract import *
from ibapi.order import *
from ibapi.order_state import *
from ibapi.execution import Execution
from ibapi.execution import ExecutionFilter
from ibapi.commission_report import CommissionReport
from ibapi.scanner import ScannerSubscription
from ibapi.ticktype import *
from ibapi.account_summary_tags import *
from ContractSamples import ContractSamples
from OrderSamples import OrderSamples
from AvailableAlgoParams import AvailableAlgoParams
from ScannerSubscriptionSamples import ScannerSubscriptionSamples
from FaAllocationSamples import FaAllocationSamples
def SetupLogger():
if not os.path.exists("log"):
os.makedirs("log")
time.strftime("pyibapi.%Y%m%d_%H%M%S.log")
recfmt = '(%(threadName)s) %(asctime)s.%(msecs)03d %(levelname)s %(filename)s:%(lineno)d %(message)s'
timefmt = '%y%m%d_%H:%M:%S'
# logging.basicConfig( level=logging.DEBUG,
# format=recfmt, datefmt=timefmt)
logging.basicConfig(filename=time.strftime("log/pyibapi.%y%m%d_%H%M%S.log"),
filemode="w",
level=logging.INFO,
format=recfmt, datefmt=timefmt)
logger = logging.getLogger()
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
logger.addHandler(console)
def printWhenExecuting(fn):
def fn2(self):
print(" doing", fn.__name__)
fn(self)
print(" done w/", fn.__name__)
return fn2
def printinstance(inst:Object):
attrs = vars(inst)
print(', '.join("%s: %s" % item for item in attrs.items()))
class Activity(Object):
def __init__(self, reqMsgId, ansMsgId, ansEndMsgId, reqId):
self.reqMsdId = reqMsgId
self.ansMsgId = ansMsgId
self.ansEndMsgId = ansEndMsgId
self.reqId = reqId
class RequestMgr(Object):
def __init__(self):
# I will keep this simple even if slower for now: only one list of
# requests finding will be done by linear search
self.requests = []
def addReq(self, req):
self.requests.append(req)
def receivedMsg(self, msg):
pass
# ! [socket_declare]
class TestClient(EClient):
def __init__(self, wrapper):
EClient.__init__(self, wrapper)
# ! [socket_declare]
# how many times a method is called to see test coverage
self.clntMeth2callCount = collections.defaultdict(int)
self.clntMeth2reqIdIdx = collections.defaultdict(lambda: -1)
self.reqId2nReq = collections.defaultdict(int)
self.setupDetectReqId()
def countReqId(self, methName, fn):
def countReqId_(*args, **kwargs):
self.clntMeth2callCount[methName] += 1
idx = self.clntMeth2reqIdIdx[methName]
if idx >= 0:
sign = -1 if 'cancel' in methName else 1
self.reqId2nReq[sign * args[idx]] += 1
return fn(*args, **kwargs)
return countReqId_
def setupDetectReqId(self):
methods = inspect.getmembers(EClient, inspect.isfunction)
for (methName, meth) in methods:
if methName != "send_msg":
# don't screw up the nice automated logging in the send_msg()
self.clntMeth2callCount[methName] = 0
# logging.debug("meth %s", name)
sig = inspect.signature(meth)
for (idx, pnameNparam) in enumerate(sig.parameters.items()):
(paramName, param) = pnameNparam
if paramName == "reqId":
self.clntMeth2reqIdIdx[methName] = idx
setattr(TestClient, methName, self.countReqId(methName, meth))
# print("TestClient.clntMeth2reqIdIdx", self.clntMeth2reqIdIdx)
# ! [ewrapperimpl]
class TestWrapper(wrapper.EWrapper):
# ! [ewrapperimpl]
def __init__(self):
wrapper.EWrapper.__init__(self)
self.wrapMeth2callCount = collections.defaultdict(int)
self.wrapMeth2reqIdIdx = collections.defaultdict(lambda: -1)
self.reqId2nAns = collections.defaultdict(int)
self.setupDetectWrapperReqId()
# TODO: see how to factor this out !!
def countWrapReqId(self, methName, fn):
def countWrapReqId_(*args, **kwargs):
self.wrapMeth2callCount[methName] += 1
idx = self.wrapMeth2reqIdIdx[methName]
if idx >= 0:
self.reqId2nAns[args[idx]] += 1
return fn(*args, **kwargs)
return countWrapReqId_
def setupDetectWrapperReqId(self):
methods = inspect.getmembers(wrapper.EWrapper, inspect.isfunction)
for (methName, meth) in methods:
self.wrapMeth2callCount[methName] = 0
# logging.debug("meth %s", name)
sig = inspect.signature(meth)
for (idx, pnameNparam) in enumerate(sig.parameters.items()):
(paramName, param) = pnameNparam
# we want to count the errors as 'error' not 'answer'
if 'error' not in methName and paramName == "reqId":
self.wrapMeth2reqIdIdx[methName] = idx
setattr(TestWrapper, methName, self.countWrapReqId(methName, meth))
# print("TestClient.wrapMeth2reqIdIdx", self.wrapMeth2reqIdIdx)
# this is here for documentation generation
"""
#! [ereader]
# You don't need to run this in your code!
self.reader = reader.EReader(self.conn, self.msg_queue)
self.reader.start() # start thread
#! [ereader]
"""
# ! [socket_init]
class TestApp(TestWrapper, TestClient):
def __init__(self):
TestWrapper.__init__(self)
TestClient.__init__(self, wrapper=self)
# ! [socket_init]
self.nKeybInt = 0
self.started = False
self.nextValidOrderId = None
self.permId2ord = {}
self.reqId2nErr = collections.defaultdict(int)
self.globalCancelOnly = False
self.simplePlaceOid = None
def dumpTestCoverageSituation(self):
for clntMeth in sorted(self.clntMeth2callCount.keys()):
logging.debug("ClntMeth: %-30s %6d" % (clntMeth,
self.clntMeth2callCount[clntMeth]))
for wrapMeth in sorted(self.wrapMeth2callCount.keys()):
logging.debug("WrapMeth: %-30s %6d" % (wrapMeth,
self.wrapMeth2callCount[wrapMeth]))
def dumpReqAnsErrSituation(self):
logging.debug("%s\t%s\t%s\t%s" % ("ReqId", "#Req", "#Ans", "#Err"))
for reqId in sorted(self.reqId2nReq.keys()):
nReq = self.reqId2nReq.get(reqId, 0)
nAns = self.reqId2nAns.get(reqId, 0)
nErr = self.reqId2nErr.get(reqId, 0)
logging.debug("%d\t%d\t%s\t%d" % (reqId, nReq, nAns, nErr))
@iswrapper
# ! [connectack]
def connectAck(self):
if self.async:
self.startApi()
# ! [connectack]
@iswrapper
# ! [nextvalidid]
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
logging.debug("setting nextValidOrderId: %d", orderId)
self.nextValidOrderId = orderId
# ! [nextvalidid]
# we can start now
self.start()
def start(self):
if self.started:
return
self.started = True
if self.globalCancelOnly:
print("Executing GlobalCancel only")
self.reqGlobalCancel()
else:
print("Executing requests")
#self.reqGlobalCancel()
#self.marketDataType_req()
#self.accountOperations_req()
#self.tickDataOperations_req()
#self.marketDepthOperations_req()
#self.realTimeBars_req()
#self.historicalDataRequests_req()
#self.optionsOperations_req()
#self.marketScanners_req()
#self.reutersFundamentals_req()
#self.bulletins_req()
#self.contractOperations_req()
#self.contractNewsFeed_req()
#self.miscelaneous_req()
#self.linkingOperations()
#self.financialAdvisorOperations()
#self.orderOperations_req()
#self.marketRuleOperations()
#self.pnlOperations()
#self.historicalTicksRequests_req()
#self.tickByTickOperations()
self.whatIfOrder_req()
print("Executing requests ... finished")
def keyboardInterrupt(self):
self.nKeybInt += 1
if self.nKeybInt == 1:
self.stop()
else:
print("Finishing test")
self.done = True
def stop(self):
print("Executing cancels")
self.orderOperations_cancel()
self.accountOperations_cancel()
self.tickDataOperations_cancel()
self.marketDepthOperations_cancel()
self.realTimeBars_cancel()
self.historicalDataRequests_cancel()
self.optionsOperations_cancel()
self.marketScanners_cancel()
self.reutersFundamentals_cancel()
self.bulletins_cancel()
print("Executing cancels ... finished")
def nextOrderId(self):
oid = self.nextValidOrderId
self.nextValidOrderId += 1
return oid
@iswrapper
# ! [error]
def error(self, reqId: TickerId, errorCode: int, errorString: str):
super().error(reqId, errorCode, errorString)
print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString)
# ! [error] self.reqId2nErr[reqId] += 1
@iswrapper
def winError(self, text: str, lastError: int):
super().winError(text, lastError)
@iswrapper
# ! [openorder]
def openOrder(self, orderId: OrderId, contract: Contract, order: Order,
orderState: OrderState):
super().openOrder(orderId, contract, order, orderState)
print("OpenOrder. ID:", orderId, contract.symbol, contract.secType,
"@", contract.exchange, ":", order.action, order.orderType,
order.totalQuantity, orderState.status)
# ! [openorder]
if order.whatIf:
print("WhatIf: ", orderId, "initMarginBefore: ", orderState.initMarginBefore, " maintMarginBefore: ", orderState.maintMarginBefore,
"equityWithLoanBefore ", orderState.equityWithLoanBefore, " initMarginChange ", orderState.initMarginChange, " maintMarginChange: ", orderState.maintMarginChange,
" equityWithLoanChange: ", orderState.equityWithLoanChange, " initMarginAfter: ", orderState.initMarginAfter, " maintMarginAfter: ", orderState.maintMarginAfter,
" equityWithLoanAfter: ", orderState.equityWithLoanAfter)
order.contract = contract
self.permId2ord[order.permId] = order
@iswrapper
# ! [openorderend]
def openOrderEnd(self):
super().openOrderEnd()
print("OpenOrderEnd")
# ! [openorderend]
logging.debug("Received %d openOrders", len(self.permId2ord))
@iswrapper
# ! [orderstatus]
def orderStatus(self, orderId: OrderId, status: str, filled: float,
remaining: float, avgFillPrice: float, permId: int,
parentId: int, lastFillPrice: float, clientId: int,
whyHeld: str, mktCapPrice: float):
super().orderStatus(orderId, status, filled, remaining,
avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice)
print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ", filled,
", Remaining: ", remaining, ", AvgFillPrice: ", avgFillPrice,
", PermId: ", permId, ", ParentId: ", parentId, ", LastFillPrice: ",
lastFillPrice, ", ClientId: ", clientId, ", WhyHeld: ",
whyHeld, ", MktCapPrice: ", mktCapPrice)
# ! [orderstatus]
@printWhenExecuting
def accountOperations_req(self):
# Requesting managed accounts***/
# ! [reqmanagedaccts]
self.reqManagedAccts()
# ! [reqmanagedaccts]
# Requesting accounts' summary ***/
# ! [reqaaccountsummary]
self.reqAccountSummary(9001, "All", AccountSummaryTags.AllTags)
# ! [reqaaccountsummary]
# ! [reqaaccountsummaryledger]
self.reqAccountSummary(9002, "All", "$LEDGER")
# ! [reqaaccountsummaryledger]
# ! [reqaaccountsummaryledgercurrency]
self.reqAccountSummary(9003, "All", "$LEDGER:EUR")
# ! [reqaaccountsummaryledgercurrency]
# ! [reqaaccountsummaryledgerall]
self.reqAccountSummary(9004, "All", "$LEDGER:ALL")
# ! [reqaaccountsummaryledgerall]
# Subscribing to an account's information. Only one at a time!
# ! [reqaaccountupdates]
self.reqAccountUpdates(True, self.account)
# ! [reqaaccountupdates]
# ! [reqaaccountupdatesmulti]
self.reqAccountUpdatesMulti(9005, self.account, "", True)
# ! [reqaaccountupdatesmulti]
# Requesting all accounts' positions.
# ! [reqpositions]
self.reqPositions()
# ! [reqpositions]
# ! [reqpositionsmulti]
self.reqPositionsMulti(9006, self.account, "")
# ! [reqpositionsmulti]
# ! [reqfamilycodes]
self.reqFamilyCodes()
# ! [reqfamilycodes]
@printWhenExecuting
def accountOperations_cancel(self):
# ! [cancelaaccountsummary]
self.cancelAccountSummary(9001)
self.cancelAccountSummary(9002)
self.cancelAccountSummary(9003)
self.cancelAccountSummary(9004)
# ! [cancelaaccountsummary]
# ! [cancelaaccountupdates]
self.reqAccountUpdates(False, self.account)
# ! [cancelaaccountupdates]
# ! [cancelaaccountupdatesmulti]
self.cancelAccountUpdatesMulti(9005)
# ! [cancelaaccountupdatesmulti]
# ! [cancelpositions]
self.cancelPositions()
# ! [cancelpositions]
# ! [cancelpositionsmulti]
self.cancelPositionsMulti(9006)
# ! [cancelpositionsmulti]
def pnlOperations(self):
# ! [reqpnl]
self.reqPnL(17001, "DU242650", "")
# ! [reqpnl]
time.sleep(1)
# ! [cancelpnl]
self.cancelPnL(17001)
# ! [cancelpnl]
# ! [reqpnlsingle]
self.reqPnLSingle(17002, "DU242650", "", 265598);
# ! [reqpnlsingle]
time.sleep(1)
# ! [cancelpnlsingle]
self.cancelPnLSingle(17002);
# ! [cancelpnlsingle]
@iswrapper
# ! [managedaccounts]
def managedAccounts(self, accountsList: str):
super().managedAccounts(accountsList)
print("Account list: ", accountsList)
# ! [managedaccounts]
self.account = accountsList.split(",")[0]
@iswrapper
# ! [accountsummary]
def accountSummary(self, reqId: int, account: str, tag: str, value: str,
currency: str):
super().accountSummary(reqId, account, tag, value, currency)
print("Acct Summary. ReqId:", reqId, "Acct:", account,
"Tag: ", tag, "Value:", value, "Currency:", currency)
# ! [accountsummary]
@iswrapper
# ! [accountsummaryend]
def accountSummaryEnd(self, reqId: int):
super().accountSummaryEnd(reqId)
print("AccountSummaryEnd. Req Id: ", reqId)
# ! [accountsummaryend]
@iswrapper
# ! [updateaccountvalue]
def updateAccountValue(self, key: str, val: str, currency: str,
accountName: str):
super().updateAccountValue(key, val, currency, accountName)
print("UpdateAccountValue. Key:", key, "Value:", val,
"Currency:", currency, "AccountName:", accountName)
# ! [updateaccountvalue]
@iswrapper
# ! [updateportfolio]
def updatePortfolio(self, contract: Contract, position: float,
marketPrice: float, marketValue: float,
averageCost: float, unrealizedPNL: float,
realizedPNL: float, accountName: str):
super().updatePortfolio(contract, position, marketPrice, marketValue,
averageCost, unrealizedPNL, realizedPNL, accountName)
print("UpdatePortfolio.", contract.symbol, "", contract.secType, "@",
contract.exchange, "Position:", position, "MarketPrice:", marketPrice,
"MarketValue:", marketValue, "AverageCost:", averageCost,
"UnrealizedPNL:", unrealizedPNL, "RealizedPNL:", realizedPNL,
"AccountName:", accountName)
# ! [updateportfolio]
@iswrapper
# ! [updateaccounttime]
def updateAccountTime(self, timeStamp: str):
super().updateAccountTime(timeStamp)
print("UpdateAccountTime. Time:", timeStamp)
# ! [updateaccounttime]
@iswrapper
# ! [accountdownloadend]
def accountDownloadEnd(self, accountName: str):
super().accountDownloadEnd(accountName)
print("Account download finished:", accountName)
# ! [accountdownloadend]
@iswrapper
# ! [position]
def position(self, account: str, contract: Contract, position: float,
avgCost: float):
super().position(account, contract, position, avgCost)
print("Position.", account, "Symbol:", contract.symbol, "SecType:",
contract.secType, "Currency:", contract.currency,
"Position:", position, "Avg cost:", avgCost)
# ! [position]
@iswrapper
# ! [positionend]
def positionEnd(self):
super().positionEnd()
print("PositionEnd")
# ! [positionend]
@iswrapper
# ! [positionmulti]
def positionMulti(self, reqId: int, account: str, modelCode: str,
contract: Contract, pos: float, avgCost: float):
super().positionMulti(reqId, account, modelCode, contract, pos, avgCost)
print("Position Multi. Request:", reqId, "Account:", account,
"ModelCode:", modelCode, "Symbol:", contract.symbol, "SecType:",
contract.secType, "Currency:", contract.currency, ",Position:",
pos, "AvgCost:", avgCost)
# ! [positionmulti]
@iswrapper
# ! [positionmultiend]
def positionMultiEnd(self, reqId: int):
super().positionMultiEnd(reqId)
print("Position Multi End. Request:", reqId)
# ! [positionmultiend]
@iswrapper
# ! [accountupdatemulti]
def accountUpdateMulti(self, reqId: int, account: str, modelCode: str,
key: str, value: str, currency: str):
super().accountUpdateMulti(reqId, account, modelCode, key, value,
currency)
print("Account Update Multi. Request:", reqId, "Account:", account,
"ModelCode:", modelCode, "Key:", key, "Value:", value,
"Currency:", currency)
# ! [accountupdatemulti]
@iswrapper
# ! [accountupdatemultiend]
def accountUpdateMultiEnd(self, reqId: int):
super().accountUpdateMultiEnd(reqId)
print("Account Update Multi End. Request:", reqId)
# ! [accountupdatemultiend]
@iswrapper
# ! [familyCodes]
def familyCodes(self, familyCodes: ListOfFamilyCode):
super().familyCodes(familyCodes)
print("Family Codes:")
for familyCode in familyCodes:
print("Account ID: %s, Family Code Str: %s" % (
familyCode.accountID, familyCode.familyCodeStr))
# ! [familyCodes]
@iswrapper
# ! [pnl]
def pnl(self, reqId: int, dailyPnL: float,
unrealizedPnL: float, realizedPnL: float):
super().pnl(reqId, dailyPnL, unrealizedPnL, realizedPnL)
print("Daily PnL. Req Id: ", reqId, ", daily PnL: ", dailyPnL,
", unrealizedPnL: ", unrealizedPnL, ", realizedPnL: ", realizedPnL)
# ! [pnl]
@iswrapper
# ! [pnlsingle]
def pnlSingle(self, reqId: int, pos: int, dailyPnL: float,
unrealizedPnL: float, realizedPnL: float, value: float):
super().pnlSingle(reqId, pos, dailyPnL, unrealizedPnL, realizedPnL, value)
print("Daily PnL Single. Req Id: ", reqId, ", pos: ", pos,
", daily PnL: ", dailyPnL, ", unrealizedPnL: ", unrealizedPnL,
", realizedPnL: ", realizedPnL, ", value: ", value)
# ! [pnlsingle]
def marketDataType_req(self):
# ! [reqmarketdatatype]
# Switch to live (1) frozen (2) delayed (3) delayed frozen (4).
self.reqMarketDataType(MarketDataTypeEnum.DELAYED)
# ! [reqmarketdatatype]
@iswrapper
# ! [marketdatatype]
def marketDataType(self, reqId: TickerId, marketDataType: int):
super().marketDataType(reqId, marketDataType)
print("MarketDataType. ", reqId, "Type:", marketDataType)
# ! [marketdatatype]
@printWhenExecuting
def tickDataOperations_req(self):
# Requesting real time market data
# ! [reqmktdata]
self.reqMktData(1000, ContractSamples.USStockAtSmart(), "", False, False, [])
self.reqMktData(1001, ContractSamples.StockComboContract(), "", True, False, [])
# ! [reqmktdata]
# ! [reqmktdata_snapshot]
self.reqMktData(1002, ContractSamples.FutureComboContract(), "", False, False, [])
# ! [reqmktdata_snapshot]
# ! [regulatorysnapshot]
# Each regulatory snapshot request incurs a 0.01 USD fee
self.reqMktData(1003, ContractSamples.USStock(), "", False, True, [])
# ! [regulatorysnapshot]
# ! [reqmktdata_genticks]
# Requesting RTVolume (Time & Sales), shortable and Fundamental Ratios generic ticks
self.reqMktData(1004, ContractSamples.USStock(), "233,236,258", False, False, [])
# ! [reqmktdata_genticks]
# ! [reqmktdata_contractnews]
# Without the API news subscription this will generate an "invalid tick type" error
self.reqMktData(1005, ContractSamples.USStock(), "mdoff,292:BZ", False, False, [])
self.reqMktData(1006, ContractSamples.USStock(), "mdoff,292:BT", False, False, [])
self.reqMktData(1007, ContractSamples.USStock(), "mdoff,292:FLY", False, False, [])
self.reqMktData(1008, ContractSamples.USStock(), "mdoff,292:MT", False, False, [])
# ! [reqmktdata_contractnews]
# ! [reqmktdata_broadtapenews]
self.reqMktData(1009, ContractSamples.BTbroadtapeNewsFeed(),
"mdoff,292", False, False, [])
self.reqMktData(1010, ContractSamples.BZbroadtapeNewsFeed(),
"mdoff,292", False, False, [])
self.reqMktData(1011, ContractSamples.FLYbroadtapeNewsFeed(),
"mdoff,292", False, False, [])
self.reqMktData(1012, ContractSamples.MTbroadtapeNewsFeed(),
"mdoff,292", False, False, [])
# ! [reqmktdata_broadtapenews]
# ! [reqoptiondatagenticks]
# Requesting data for an option contract will return the greek values
self.reqMktData(1013, ContractSamples.OptionWithLocalSymbol(), "", False, False, [])
# ! [reqoptiondatagenticks]
# ! [reqsmartcomponents]
# Requests description of map of single letter exchange codes to full exchange names
self.reqSmartComponents(1013, "a6")
# ! [reqsmartcomponents]
# ! [reqfuturesopeninterest]
self.reqMktData(1014, ContractSamples.SimpleFuture(), "mdoff,588", False, False, [])
# ! [reqfuturesopeninterest]
# ! [reqmktdatapreopenbidask]
self.reqMktData(1015, ContractSamples.SimpleFuture(), "", False, False, [])
# ! [reqmktdatapreopenbidask]
# ! [reqavgoptvolume]
self.reqMktData(1016, ContractSamples.USStockAtSmart(), "mdoff,105", False, False, [])
# ! [reqavgoptvolume]
@printWhenExecuting
def tickDataOperations_cancel(self):
# Canceling the market data subscription
# ! [cancelmktdata]
self.cancelMktData(1000)
self.cancelMktData(1001)
self.cancelMktData(1002)
self.cancelMktData(1003)
# ! [cancelmktdata]
self.cancelMktData(1004)
self.cancelMktData(1005)
self.cancelMktData(1006)
self.cancelMktData(1007)
self.cancelMktData(1008)
self.cancelMktData(1009)
self.cancelMktData(1010)
self.cancelMktData(1011)
self.cancelMktData(1012)
self.cancelMktData(1013)
self.cancelMktData(1014)
self.cancelMktData(1015)
self.cancelMktData(1016)
@iswrapper
# ! [tickprice]
def tickPrice(self, reqId: TickerId, tickType: TickType, price: float,
attrib: TickAttrib):
super().tickPrice(reqId, tickType, price, attrib)
print("Tick Price. Ticker Id:", reqId, "tickType:", tickType,
"Price:", price, "CanAutoExecute:", attrib.canAutoExecute,
"PastLimit:", attrib.pastLimit, end=' ')
if tickType == TickTypeEnum.BID or tickType == TickTypeEnum.ASK:
print("PreOpen:", attrib.preOpen)
else:
print()
# ! [tickprice]
@iswrapper
# ! [ticksize]
def tickSize(self, reqId: TickerId, tickType: TickType, size: int):
super().tickSize(reqId, tickType, size)
print("Tick Size. Ticker Id:", reqId, "tickType:", tickType, "Size:", size)
# ! [ticksize]
@iswrapper
# ! [tickgeneric]
def tickGeneric(self, reqId: TickerId, tickType: TickType, value: float):
super().tickGeneric(reqId, tickType, value)
print("Tick Generic. Ticker Id:", reqId, "tickType:", tickType, "Value:", value)
# ! [tickgeneric]
@iswrapper
# ! [tickstring]
def tickString(self, reqId: TickerId, tickType: TickType, value: str):
super().tickString(reqId, tickType, value)
print("Tick string. Ticker Id:", reqId, "Type:", tickType, "Value:", value)
# ! [tickstring]
@iswrapper
# ! [ticksnapshotend]
def tickSnapshotEnd(self, reqId: int):
super().tickSnapshotEnd(reqId)
print("TickSnapshotEnd:", reqId)
# ! [ticksnapshotend]
@iswrapper
# ! [rerouteMktDataReq]
def rerouteMktDataReq(self, reqId: int, conId: int, exchange: str):
super().rerouteMktDataReq(reqId, conId, exchange)
print("Re-route market data request. Req Id: ", reqId,
", ConId: ", conId, " Exchange: ", exchange)
# ! [rerouteMktDataReq]
@iswrapper
# ! [marketRule]
def marketRule(self, marketRuleId: int, priceIncrements: ListOfPriceIncrements):
super().marketRule(marketRuleId, priceIncrements)
print("Market Rule ID: ", marketRuleId)
for priceIncrement in priceIncrements:
print("Price Increment. Low Edge: ", priceIncrement.lowEdge,
", Increment: ", priceIncrement.increment)
# ! [marketRule]
@printWhenExecuting
def tickByTickOperations(self):
# Requesting tick-by-tick data (only refresh)
# ! [reqtickbytick]
self.reqTickByTickData(19001, ContractSamples.USStockAtSmart(), "Last", 0, True)
self.reqTickByTickData(19002, ContractSamples.USStockAtSmart(), "AllLast", 0, False)
self.reqTickByTickData(19003, ContractSamples.USStockAtSmart(), "BidAsk", 0, True)
self.reqTickByTickData(19004, ContractSamples.USStockAtSmart(), "MidPoint", 0, False)
# ! [reqtickbytick]
time.sleep(1)
# ! [canceltickbytick]
self.cancelTickByTickData(19001)
self.cancelTickByTickData(19002)
self.cancelTickByTickData(19003)
self.cancelTickByTickData(19004)
# ! [canceltickbytick]
# Requesting tick-by-tick data (refresh + historicalticks)
# ! [reqtickbytickwithhist]
self.reqTickByTickData(19001, ContractSamples.EuropeanStock(), "Last", 10, False)
self.reqTickByTickData(19002, ContractSamples.EuropeanStock(), "AllLast", 10, False)
self.reqTickByTickData(19003, ContractSamples.EuropeanStock(), "BidAsk", 10, False)
self.reqTickByTickData(19004, ContractSamples.EurGbpFx(), "MidPoint", 10, True)
# ! [reqtickbytickwithhist]
time.sleep(1)
# ! [canceltickbytickwithhist]
self.cancelTickByTickData(19005)
self.cancelTickByTickData(19006)
self.cancelTickByTickData(19007)
self.cancelTickByTickData(19008)
# ! [canceltickbytickwithhist]
@iswrapper
# ! [tickbytickalllast]
def tickByTickAllLast(self, reqId: int, tickType: int, time: int, price: float,
size: int, attribs: TickAttrib, exchange: str,
specialConditions: str):
super().tickByTickAllLast(reqId, tickType, time, price, size, attribs,
exchange, specialConditions)
if tickType == 1:
print("Last.", end='')
else:
print("AllLast.", end='')
print(" ReqId: ", reqId,
" Time: ", datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
" Price: ", price, " Size: ", size, " Exch: " , exchange,
"Spec Cond: ", specialConditions, end='')
if attribs.pastLimit:
print(" pastLimit ", end='')
if attribs.unreported:
print(" unreported", end='')
print()
# ! [tickbytickalllast]
@iswrapper
# ! [tickbytickbidask]
def tickByTickBidAsk(self, reqId: int, time: int, bidPrice: float, askPrice: float,
bidSize: int, askSize: int, attribs: TickAttrib):
super().tickByTickBidAsk(reqId, time, bidPrice, askPrice, bidSize,
askSize, attribs)
print("BidAsk. Req Id: ", reqId,
" Time: ", datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
" BidPrice: ", bidPrice, " AskPrice: ", askPrice, " BidSize: ", bidSize,
" AskSize: ", askSize, end='')
if attribs.bidPastLow:
print(" bidPastLow", end='')
if attribs.askPastHigh:
print(" askPastHigh", end='')
print()
# ! [tickbytickbidask]
# ! [tickbytickmidpoint]
@iswrapper
def tickByTickMidPoint(self, reqId: int, time: int, midPoint: float):
super().tickByTickMidPoint(reqId, time, midPoint)
print("Midpoint. Req Id: ", reqId,
" Time: ", datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
" MidPoint: ", midPoint)
# ! [tickbytickmidpoint]
@printWhenExecuting
def marketDepthOperations_req(self):
# Requesting the Deep Book
# ! [reqmarketdepth]
self.reqMktDepth(2101, ContractSamples.USStock(), 5, [])
self.reqMktDepth(2001, ContractSamples.EurGbpFx(), 5, [])
# ! [reqmarketdepth]
# Request list of exchanges sending market depth to UpdateMktDepthL2()
# ! [reqMktDepthExchanges]
self.reqMktDepthExchanges()
# ! [reqMktDepthExchanges]
@iswrapper
# ! [updatemktdepth]
def updateMktDepth(self, reqId: TickerId, position: int, operation: int,
side: int, price: float, size: int):
super().updateMktDepth(reqId, position, operation, side, price, size)
print("UpdateMarketDepth. ", reqId, "Position:", position, "Operation:",
operation, "Side:", side, "Price:", price, "Size", size)
# ! [updatemktdepth]
@iswrapper
# ! [updatemktdepthl2]
def updateMktDepthL2(self, reqId: TickerId, position: int, marketMaker: str,
operation: int, side: int, price: float, size: int):
super().updateMktDepthL2(reqId, position, marketMaker, operation, side,
price, size)
print("UpdateMarketDepthL2. ", reqId, "Position:", position, "Operation:",
operation, "Side:", side, "Price:", price, "Size", size)
# ! [updatemktdepthl2]
@iswrapper
# ! [rerouteMktDepthReq]
def rerouteMktDepthReq(self, reqId: int, conId: int, exchange: str):
super().rerouteMktDataReq(reqId, conId, exchange)
print("Re-route market data request. Req Id: ", reqId,
", ConId: ", conId, " Exchange: ", exchange)
# ! [rerouteMktDepthReq]
@printWhenExecuting
def marketDepthOperations_cancel(self):
# Canceling the Deep Book request
# ! [cancelmktdepth]
self.cancelMktDepth(2101)
self.cancelMktDepth(2001)
# ! [cancelmktdepth]
@printWhenExecuting
def realTimeBars_req(self):
# Requesting real time bars
# ! [reqrealtimebars]
self.reqRealTimeBars(3101, ContractSamples.USStockAtSmart(), 5, "MIDPOINT", True, [])
self.reqRealTimeBars(3001, ContractSamples.EurGbpFx(), 5, "MIDPOINT", True, [])
# ! [reqrealtimebars]
@iswrapper
# ! [realtimebar]
def realtimeBar(self, reqId:TickerId, time:int, open:float, high:float,
low:float, close:float, volume:int, wap:float, count:int):
super().realtimeBar(reqId, time, open, high, low, close, volume, wap, count)
print("RealTimeBars. ", reqId, ": time ", time, ", open: ",open,
", high: ", high, ", low: ", low, ", close: ", close, ", volume: ", volume,
", wap: ", wap, ", count: ", count)
# ! [realtimebar]
@printWhenExecuting
def realTimeBars_cancel(self):
# Canceling real time bars
# ! [cancelrealtimebars]
self.cancelRealTimeBars(3101)
self.cancelRealTimeBars(3001)
# ! [cancelrealtimebars]
@printWhenExecuting
def historicalDataRequests_req(self):
# Requesting historical data
# ! [reqHeadTimeStamp]
self.reqHeadTimeStamp(4103, ContractSamples.USStockAtSmart(), "TRADES", 0, 1)
# ! [reqHeadTimeStamp]
time.sleep(1)
# ! [cancelHeadTimestamp]
self.cancelHeadTimeStamp(4103)
# ! [cancelHeadTimestamp]
# ! [reqhistoricaldata]
queryTime = (datetime.datetime.today() -
datetime.timedelta(days=180)).strftime("%Y%m%d %H:%M:%S")
self.reqHistoricalData(4101, ContractSamples.USStockAtSmart(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
self.reqHistoricalData(4001, ContractSamples.EurGbpFx(), queryTime,
"1 M", "1 day", "MIDPOINT", 1, 1, False, [])
self.reqHistoricalData(4002, ContractSamples.EuropeanStock(), queryTime,
"10 D", "1 min", "TRADES", 1, 1, False, [])
# ! [reqhistoricaldata]
# ! [reqHistogramData]
self.reqHistogramData(4104, ContractSamples.USStock(), False, "3 days")
# ! [reqHistogramData]
time.sleep(2)
# ! [cancelHistogramData]
self.cancelHistogramData(4104)
# ! [cancelHistogramData]
@printWhenExecuting
def historicalDataRequests_cancel(self):
# Canceling historical data requests
self.cancelHistoricalData(4101)
self.cancelHistoricalData(4001)
self.cancelHistoricalData(4002)
@printWhenExecuting
def historicalTicksRequests_req(self):
# ! [reqhistoricalticks]
self.reqHistoricalTicks(18001, ContractSamples.USStockAtSmart(),
"20170712 21:39:33", "", 10, "TRADES", 1, True, [])
self.reqHistoricalTicks(18002, ContractSamples.USStockAtSmart(),
"20170712 21:39:33", "", 10, "BID_ASK", 1, True, [])
self.reqHistoricalTicks(18003, ContractSamples.USStockAtSmart(),
"20170712 21:39:33", "", 10, "MIDPOINT", 1, True, [])
# ! [reqhistoricalticks]
@iswrapper
# ! [headTimestamp]
def headTimestamp(self, reqId:int, headTimestamp:str):
print("HeadTimestamp: ", reqId, " ", headTimestamp)
# ! [headTimestamp]
@iswrapper
# ! [histogramData]
def histogramData(self, reqId:int, items:HistogramDataList):
print("HistogramData: ", reqId, " ", items)
# ! [histogramData]
@iswrapper
# ! [historicaldata]
def historicalData(self, reqId:int, bar: BarData):
print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open,
"High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
"Count:", bar.barCount, "WAP:", bar.average)
# ! [historicaldata]
@iswrapper
# ! [historicaldataend]
def historicalDataEnd(self, reqId: int, start: str, end: str):
super().historicalDataEnd(reqId, start, end)
print("HistoricalDataEnd ", reqId, "from", start, "to", end)
# ! [historicaldataend]
@iswrapper
# ! [historicalDataUpdate]
def historicalDataUpdate(self, reqId: int, bar: BarData):
print("HistoricalDataUpdate. ", reqId, " Date:", bar.date, "Open:", bar.open,
"High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume,
"Count:", bar.barCount, "WAP:", bar.average)
# ! [historicalDataUpdate]
@iswrapper
# ! [historicalticks]
def historicalTicks(self, reqId: int, ticks: ListOfHistoricalTick, done: bool):
for tick in ticks:
print("Historical Tick. Req Id: ", reqId, ", time: ", tick.time,
", price: ", tick.price, ", size: ", tick.size)
# ! [historicalticks]
@iswrapper
# ! [historicalticksbidask]
def historicalTicksBidAsk(self, reqId: int, ticks: ListOfHistoricalTickBidAsk,
done: bool):
for tick in ticks:
print("Historical Tick Bid/Ask. Req Id: ", reqId, ", time: ", tick.time,
", bid price: ", tick.priceBid, ", ask price: ", tick.priceAsk,
", bid size: ", tick.sizeBid, ", ask size: ", tick.sizeAsk)
# ! [historicalticksbidask]
@iswrapper
# ! [historicaltickslast]
def historicalTicksLast(self, reqId: int, ticks: ListOfHistoricalTickLast,
done: bool):
for tick in ticks:
print("Historical Tick Last. Req Id: ", reqId, ", time: ", tick.time,
", price: ", tick.price, ", size: ", tick.size, ", exchange: ", tick.exchange,
", special conditions:", tick.specialConditions)
# ! [historicaltickslast]
@printWhenExecuting
def optionsOperations_req(self):
# ! [reqsecdefoptparams]
self.reqSecDefOptParams(0, "IBM", "", "STK", 8314)
# ! [reqsecdefoptparams]
# Calculating implied volatility
# ! [calculateimpliedvolatility]
self.calculateImpliedVolatility(5001, ContractSamples.OptionAtBOX(), 5, 85, [])
# ! [calculateimpliedvolatility]
# Calculating option's price
# ! [calculateoptionprice]
self.calculateOptionPrice(5002, ContractSamples.OptionAtBOX(), 0.22, 85, [])
# ! [calculateoptionprice]
# Exercising options
# ! [exercise_options]
self.exerciseOptions(5003, ContractSamples.OptionWithTradingClass(), 1,
1, self.account, 1)
# ! [exercise_options]
@printWhenExecuting
def optionsOperations_cancel(self):
# Canceling implied volatility
self.cancelCalculateImpliedVolatility(5001)
# Canceling option's price calculation
self.cancelCalculateOptionPrice(5002)
@iswrapper
# ! [securityDefinitionOptionParameter]
def securityDefinitionOptionParameter(self, reqId: int, exchange: str,
underlyingConId: int, tradingClass: str, multiplier: str,
expirations: SetOfString, strikes: SetOfFloat):
super().securityDefinitionOptionParameter(reqId, exchange,
underlyingConId, tradingClass, multiplier, expirations, strikes)
print("Security Definition Option Parameter. ReqId:%d Exchange:%s "
"Underlying conId: %d TradingClass:%s Multiplier:%s Exp:%s Strikes:%s",
reqId, exchange, underlyingConId, tradingClass, multiplier,
",".join(expirations), ",".join(str(strikes)))
# ! [securityDefinitionOptionParameter]
@iswrapper
# ! [securityDefinitionOptionParameterEnd]
def securityDefinitionOptionParameterEnd(self, reqId: int):
super().securityDefinitionOptionParameterEnd(reqId)
print("Security Definition Option Parameter End. Request: ", reqId)
# ! [securityDefinitionOptionParameterEnd]
@iswrapper
# ! [tickoptioncomputation]
def tickOptionComputation(self, reqId: TickerId, tickType: TickType,
impliedVol: float, delta: float, optPrice: float, pvDividend: float,
gamma: float, vega: float, theta: float, undPrice: float):
super().tickOptionComputation(reqId, tickType, impliedVol, delta,
optPrice, pvDividend, gamma, vega, theta, undPrice)
print("TickOptionComputation. TickerId:", reqId, "tickType:", tickType,
"ImpliedVolatility:", impliedVol, "Delta:", delta, "OptionPrice:",
optPrice, "pvDividend:", pvDividend, "Gamma: ", gamma, "Vega:", vega,
"Theta:", theta, "UnderlyingPrice:", undPrice)
# ! [tickoptioncomputation]
@printWhenExecuting
def contractOperations_req(self):
# ! [reqcontractdetails]
self.reqContractDetails(209, ContractSamples.EurGbpFx())
self.reqContractDetails(210, ContractSamples.OptionForQuery())
self.reqContractDetails(211, ContractSamples.Bond())
self.reqContractDetails(212, ContractSamples.FuturesOnOptions())
# ! [reqcontractdetails]
# ! [reqmatchingsymbols]
self.reqMatchingSymbols(212, "IB")
# ! [reqmatchingsymbols]
@printWhenExecuting
def contractNewsFeed_req(self):
# ! [reqcontractdetailsnews]
self.reqContractDetails(213, ContractSamples.NewsFeedForQuery())
# ! [reqcontractdetailsnews]
# Returns list of subscribed news providers
# ! [reqNewsProviders]
self.reqNewsProviders()
# ! [reqNewsProviders]
# Returns body of news article given article ID
# ! [reqNewsArticle]
self.reqNewsArticle(214,"BZ", "BZ$04507322", [])
# ! [reqNewsArticle]
# Returns list of historical news headlines with IDs
# ! [reqHistoricalNews]
self.reqHistoricalNews(215, 8314, "BZ+FLY", "", "", 10, [])
# ! [reqHistoricalNews]
@iswrapper
#! [tickNews]
def tickNews(self, tickerId: int, timeStamp: int, providerCode: str,
articleId: str, headline: str, extraData: str):
print("tickNews: ", tickerId, ", timeStamp: ", timeStamp,
", providerCode: ", providerCode, ", articleId: ", articleId,
", headline: ", headline, "extraData: ", extraData)
#! [tickNews]
@iswrapper
#! [historicalNews]
def historicalNews(self, reqId: int, time: str, providerCode: str,
articleId: str, headline: str):
print("historicalNews: ", reqId, ", time: ", time,
", providerCode: ", providerCode, ", articleId: ", articleId,
", headline: ", headline)
#! [historicalNews]
@iswrapper
#! [historicalNewsEnd]
def historicalNewsEnd(self, reqId:int, hasMore:bool):
print("historicalNewsEnd: ", reqId, ", hasMore: ", hasMore)
#! [historicalNewsEnd]
@iswrapper
#! [newsProviders]
def newsProviders(self, newsProviders: ListOfNewsProviders):
print("newsProviders: ")
for provider in newsProviders:
print(provider)
#! [newsProviders]
@iswrapper
#! [newsArticle]
def newsArticle(self, reqId: int, articleType: int, articleText: str):
print("newsArticle: ", reqId, ", articleType: ", articleType,
", articleText: ", articleText)
#! [newsArticle]
@iswrapper
# ! [contractdetails]
def contractDetails(self, reqId: int, contractDetails: ContractDetails):
super().contractDetails(reqId, contractDetails)
printinstance(contractDetails.contract)
# ! [contractdetails]
@iswrapper
# ! [bondcontractdetails]
def bondContractDetails(self, reqId: int, contractDetails: ContractDetails):
super().bondContractDetails(reqId, contractDetails)
# ! [bondcontractdetails]
@iswrapper
# ! [contractdetailsend]
def contractDetailsEnd(self, reqId: int):
super().contractDetailsEnd(reqId)
print("ContractDetailsEnd. ", reqId, "\n")
# ! [contractdetailsend]
@iswrapper
# ! [symbolSamples]
def symbolSamples(self, reqId: int,
contractDescriptions: ListOfContractDescription):
super().symbolSamples(reqId, contractDescriptions)
print("Symbol Samples. Request Id: ", reqId)
for contractDescription in contractDescriptions:
derivSecTypes = ""
for derivSecType in contractDescription.derivativeSecTypes:
derivSecTypes += derivSecType
derivSecTypes += " "
print("Contract: conId:%s, symbol:%s, secType:%s primExchange:%s, "
"currency:%s, derivativeSecTypes:%s" % (
contractDescription.contract.conId,
contractDescription.contract.symbol,
contractDescription.contract.secType,
contractDescription.contract.primaryExchange,
contractDescription.contract.currency, derivSecTypes))
# ! [symbolSamples]
@printWhenExecuting
def marketScanners_req(self):
# Requesting list of valid scanner parameters which can be used in TWS
# ! [reqscannerparameters]
self.reqScannerParameters()
# ! [reqscannerparameters]
# Triggering a scanner subscription
# ! [reqscannersubscription]
self.reqScannerSubscription(7001,
ScannerSubscriptionSamples.HighOptVolumePCRatioUSIndexes(), [])
# ! [reqscannersubscription]
@printWhenExecuting
def marketScanners_cancel(self):
# Canceling the scanner subscription
# ! [cancelscannersubscription]
self.cancelScannerSubscription(7001)
# ! [cancelscannersubscription]
@iswrapper
# ! [scannerparameters]
def scannerParameters(self, xml: str):
super().scannerParameters(xml)
open('log/scanner.xml', 'w').write(xml)
# ! [scannerparameters]
@iswrapper
# ! [scannerdata]
def scannerData(self, reqId: int, rank: int, contractDetails: ContractDetails,
distance: str, benchmark: str, projection: str, legsStr: str):
super().scannerData(reqId, rank, contractDetails, distance, benchmark,
projection, legsStr)
print("ScannerData. ", reqId, "Rank:", rank, "Symbol:", contractDetails.contract.symbol,
"SecType:", contractDetails.contract.secType,
"Currency:", contractDetails.contract.currency,
"Distance:", distance, "Benchmark:", benchmark,
"Projection:", projection, "Legs String:", legsStr)
# ! [scannerdata]
@iswrapper
# ! [scannerdataend]
def scannerDataEnd(self, reqId: int):
super().scannerDataEnd(reqId)
print("ScannerDataEnd. ", reqId)
# ! [scannerdataend]
@iswrapper
# ! [smartcomponents]
def smartComponents(self, reqId:int, map:SmartComponentMap):
super().smartComponents(reqId, map)
print("smartComponents: ")
for exch in map:
print(exch.bitNumber, ", Exchange Name: ", exch.exchange,
", Letter: ", exch.exchangeLetter)
# ! [smartcomponents]
@iswrapper
# ! [tickReqParams]
def tickReqParams(self, tickerId:int, minTick:float,
bboExchange:str, snapshotPermissions:int):
super().tickReqParams(tickerId, minTick, bboExchange, snapshotPermissions)
print("tickReqParams: ", tickerId, " minTick: ", minTick,
" bboExchange: ", bboExchange, " snapshotPermissions: ", snapshotPermissions)
# ! [tickReqParams]
@iswrapper
# ! [mktDepthExchanges]
def mktDepthExchanges(self, depthMktDataDescriptions:ListOfDepthExchanges):
super().mktDepthExchanges(depthMktDataDescriptions)
print("mktDepthExchanges:")
for desc in depthMktDataDescriptions:
printinstance(desc)
# ! [mktDepthExchanges]
@printWhenExecuting
def reutersFundamentals_req(self):
# Requesting Fundamentals
# ! [reqfundamentaldata]
self.reqFundamentalData(8001, ContractSamples.USStock(),
"ReportsFinSummary", [])
# ! [reqfundamentaldata]
@printWhenExecuting
def reutersFundamentals_cancel(self):
# Canceling fundamentals request ***/
# ! [cancelfundamentaldata]
self.cancelFundamentalData(8001)
# ! [cancelfundamentaldata]
@iswrapper
# ! [fundamentaldata]
def fundamentalData(self, reqId: TickerId, data: str):
super().fundamentalData(reqId, data)
print("FundamentalData. ", reqId, data)
# ! [fundamentaldata]
@printWhenExecuting
def bulletins_req(self):
# Requesting Interactive Broker's news bulletins
# ! [reqnewsbulletins]
self.reqNewsBulletins(True)
# ! [reqnewsbulletins]
@printWhenExecuting
def bulletins_cancel(self):
# Canceling IB's news bulletins
# ! [cancelnewsbulletins]
self.cancelNewsBulletins()
# ! [cancelnewsbulletins]
@iswrapper
# ! [updatenewsbulletin]
def updateNewsBulletin(self, msgId: int, msgType: int, newsMessage: str,
originExch: str):
super().updateNewsBulletin(msgId, msgType, newsMessage, originExch)
print("News Bulletins. ", msgId, " Type: ", msgType, "Message:", newsMessage,
"Exchange of Origin: ", originExch)
# ! [updatenewsbulletin]
self.bulletins_cancel()
def ocaSample(self):
# OCA ORDER
# ! [ocasubmit]
ocaOrders = [OrderSamples.LimitOrder("BUY", 1, 10), OrderSamples.LimitOrder("BUY", 1, 11),
OrderSamples.LimitOrder("BUY", 1, 12)]
OrderSamples.OneCancelsAll("TestOCA_" + self.nextValidOrderId, ocaOrders, 2)
for o in ocaOrders:
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), o)
# ! [ocasubmit]
def conditionSamples(self):
# ! [order_conditioning_activate]
mkt = OrderSamples.MarketOrder("BUY", 100)
# Order will become active if conditioning criteria is met
mkt.conditionsCancelOrder = True
mkt.conditions.append(
OrderSamples.PriceCondition(PriceCondition.TriggerMethodEnum.Default,
208813720, "SMART", 600, False, False))
mkt.conditions.append(OrderSamples.ExecutionCondition("EUR.USD", "CASH", "IDEALPRO", True))
mkt.conditions.append(OrderSamples.MarginCondition(30, True, False))
mkt.conditions.append(OrderSamples.PercentageChangeCondition(15.0, 208813720, "SMART", True, True))
mkt.conditions.append(OrderSamples.TimeCondition("20160118 23:59:59", True, False))
mkt.conditions.append(OrderSamples.VolumeCondition(208813720, "SMART", False, 100, True))
self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), mkt)
# ! [order_conditioning_activate]
# Conditions can make the order active or cancel it. Only LMT orders can be conditionally canceled.
# ! [order_conditioning_cancel]
lmt = OrderSamples.LimitOrder("BUY", 100, 20)
# The active order will be cancelled if conditioning criteria is met
lmt.conditionsCancelOrder = True
lmt.conditions.append(
OrderSamples.PriceCondition(PriceCondition.TriggerMethodEnum.Last,
208813720, "SMART", 600, False, False))
self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), lmt)
# ! [order_conditioning_cancel]
def bracketSample(self):
# BRACKET ORDER
# ! [bracketsubmit]
bracket = OrderSamples.BracketOrder(self.nextOrderId(), "BUY", 100, 30, 40, 20)
for o in bracket:
self.placeOrder(o.orderId, ContractSamples.EuropeanStock(), o)
self.nextOrderId() # need to advance this we'll skip one extra oid, it's fine
# ! [bracketsubmit]
def hedgeSample(self):
# F Hedge order
# ! [hedgesubmit]
# Parent order on a contract which currency differs from your base currency
parent = OrderSamples.LimitOrder("BUY", 100, 10)
parent.orderId = self.nextOrderId()
# Hedge on the currency conversion
hedge = OrderSamples.MarketFHedge(parent.orderId, "BUY")
# Place the parent first...
self.placeOrder(parent.orderId, ContractSamples.EuropeanStock(), parent)
# Then the hedge order
self.placeOrder(self.nextOrderId(), ContractSamples.EurGbpFx(), hedge)
# ! [hedgesubmit]
def testAlgoSamples(self):
# ! [algo_base_order]
baseOrder = OrderSamples.LimitOrder("BUY", 1000, 1)
# ! [algo_base_order]
# ! [arrivalpx]
AvailableAlgoParams.FillArrivalPriceParams(baseOrder, 0.1,
"Aggressive", "09:00:00 CET", "16:00:00 CET", True, True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [arrivalpx]
# ! [darkice]
AvailableAlgoParams.FillDarkIceParams(baseOrder, 10,
"09:00:00 CET", "16:00:00 CET", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [darkice]
# ! [ad]
# The Time Zone in "startTime" and "endTime" attributes is ignored and always defaulted to GMT
AvailableAlgoParams.FillAccumulateDistributeParams(baseOrder, 10, 60,
True, True, 1, True, True,
"20161010-12:00:00 GMT", "20161010-16:00:00 GMT")
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [ad]
# ! [twap]
AvailableAlgoParams.FillTwapParams(baseOrder, "Marketable",
"09:00:00 CET", "16:00:00 CET", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [twap]
# ! [vwap]
AvailableAlgoParams.FillVwapParams(baseOrder, 0.2,
"09:00:00 CET", "16:00:00 CET", True, True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [vwap]
# ! [balanceimpactrisk]
AvailableAlgoParams.FillBalanceImpactRiskParams(baseOrder, 0.1,
"Aggressive", True)
self.placeOrder(self.nextOrderId(), ContractSamples.USOptionContract(), baseOrder)
# ! [balanceimpactrisk]
# ! [minimpact]
AvailableAlgoParams.FillMinImpactParams(baseOrder, 0.3)
self.placeOrder(self.nextOrderId(), ContractSamples.USOptionContract(), baseOrder)
# ! [minimpact]
# ! [adaptive]
AvailableAlgoParams.FillAdaptiveParams(baseOrder, "Normal")
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [adaptive]
# ! [closepx]
AvailableAlgoParams.FillClosePriceParams(baseOrder, 0.5, "Neutral",
"12:00:00 EST", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [closepx]
# ! [pctvol]
AvailableAlgoParams.FillPctVolParams(baseOrder, 0.5,
"12:00:00 EST", "14:00:00 EST", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [pctvol]
# ! [pctvolpx]
AvailableAlgoParams.FillPriceVariantPctVolParams(baseOrder,
0.1, 0.05, 0.01, 0.2, "12:00:00 EST", "14:00:00 EST", True,
100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [pctvolpx]
# ! [pctvolsz]
AvailableAlgoParams.FillSizeVariantPctVolParams(baseOrder,
0.2, 0.4, "12:00:00 EST", "14:00:00 EST", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [pctvolsz]
# ! [pctvoltm]
AvailableAlgoParams.FillTimeVariantPctVolParams(baseOrder,
0.2, 0.4, "12:00:00 EST", "14:00:00 EST", True, 100000)
self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), baseOrder)
# ! [pctvoltm]
# ! [jeff_vwap_algo]
AvailableAlgoParams.FillJefferiesVWAPParams(baseOrder,
"10:00:00 EST", "16:00:00 EST", 10, 10, "Exclude_Both",
130, 135, 1, 10, "Patience", False, "Midpoint")
self.placeOrder(self.nextOrderId(), ContractSamples.JefferiesContract(), baseOrder)
# ! [jeff_vwap_algo]
# ! [csfb_inline_algo]
AvailableAlgoParams.FillCSFBInlineParams(baseOrder,
"10:00:00 EST", "16:00:00 EST", "Patient",
10, 20, 100, "Default", False, 40, 100, 100, 35)
self.placeOrder(self.nextOrderId(), ContractSamples.CSFBContract(), baseOrder)
# ! [csfb_inline_algo]
@printWhenExecuting
def financialAdvisorOperations(self):
# Requesting FA information ***/
# ! [requestfaaliases]
self.requestFA(FaDataTypeEnum.ALIASES)
# ! [requestfaaliases]
# ! [requestfagroups]
self.requestFA(FaDataTypeEnum.GROUPS)
# ! [requestfagroups]
# ! [requestfaprofiles]
self.requestFA(FaDataTypeEnum.PROFILES)
# ! [requestfaprofiles]
# Replacing FA information - Fill in with the appropriate XML string. ***/
# ! [replacefaonegroup]
self.replaceFA(FaDataTypeEnum.GROUPS, FaAllocationSamples.FaOneGroup)
# ! [replacefaonegroup]
# ! [replacefatwogroups]
self.replaceFA(FaDataTypeEnum.GROUPS, FaAllocationSamples.FaTwoGroups)
# ! [replacefatwogroups]
# ! [replacefaoneprofile]
self.replaceFA(FaDataTypeEnum.PROFILES, FaAllocationSamples.FaOneProfile)
# ! [replacefaoneprofile]
# ! [replacefatwoprofiles]
self.replaceFA(FaDataTypeEnum.PROFILES, FaAllocationSamples.FaTwoProfiles)
# ! [replacefatwoprofiles]
# ! [reqSoftDollarTiers]
self.reqSoftDollarTiers(14001)
# ! [reqSoftDollarTiers]
@iswrapper
# ! [receivefa]
def receiveFA(self, faData: FaDataType, cxml: str):
super().receiveFA(faData, cxml)
print("Receiving FA: ", faData)
open('log/fa.xml', 'w').write(cxml)
# ! [receivefa]
@iswrapper
# ! [softDollarTiers]
def softDollarTiers(self, reqId: int, tiers: list):
super().softDollarTiers(reqId, tiers)
print("Soft Dollar Tiers:", tiers)
# ! [softDollarTiers]
@printWhenExecuting
def miscelaneous_req(self):
# Request TWS' current time ***/
self.reqCurrentTime()
# Setting TWS logging level ***/
self.setServerLogLevel(1)
@printWhenExecuting
def linkingOperations(self):
# ! [querydisplaygroups]
self.queryDisplayGroups(19001)
# ! [querydisplaygroups]
# ! [subscribetogroupevents]
self.subscribeToGroupEvents(19002, 1)
# ! [subscribetogroupevents]
# ! [updatedisplaygroup]
self.updateDisplayGroup(19002, "8314@SMART")
# ! [updatedisplaygroup]
# ! [subscribefromgroupevents]
self.unsubscribeFromGroupEvents(19002)
# ! [subscribefromgroupevents]
@iswrapper
# ! [displaygrouplist]
def displayGroupList(self, reqId: int, groups: str):
super().displayGroupList(reqId, groups)
print("DisplayGroupList. Request: ", reqId, "Groups", groups)
# ! [displaygrouplist]
@iswrapper
# ! [displaygroupupdated]
def displayGroupUpdated(self, reqId: int, contractInfo: str):
super().displayGroupUpdated(reqId, contractInfo)
print("displayGroupUpdated. Request:", reqId, "ContractInfo:", contractInfo)
# ! [displaygroupupdated]
@printWhenExecuting
def whatIfOrder_req(self):
# ! [whatiflimitorder]
whatIfOrder = OrderSamples.LimitOrder("SELL", 5, 70)
whatIfOrder.whatIf = True
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), whatIfOrder)
# ! [whatiflimitorder]
time.sleep(2)
@printWhenExecuting
def orderOperations_req(self):
# Requesting the next valid id ***/
# ! [reqids]
# The parameter is always ignored.
self.reqIds(-1)
# ! [reqids]
# Requesting all open orders ***/
# ! [reqallopenorders]
self.reqAllOpenOrders()
# ! [reqallopenorders]
# Taking over orders to be submitted via TWS ***/
# ! [reqautoopenorders]
self.reqAutoOpenOrders(True)
# ! [reqautoopenorders]
# Requesting this API client's orders ***/
# ! [reqopenorders]
self.reqOpenOrders()
# ! [reqopenorders]
# Placing/modifying an order - remember to ALWAYS increment the
# nextValidId after placing an order so it can be used for the next one!
# Note if there are multiple clients connected to an account, the
# order ID must also be greater than all order IDs returned for orders
# to orderStatus and openOrder to this client.
# ! [order_submission]
self.simplePlaceOid = self.nextOrderId()
self.placeOrder(self.simplePlaceOid, ContractSamples.USStock(),
OrderSamples.LimitOrder("SELL", 1, 50))
# ! [order_submission]
# ! [faorderoneaccount]
faOrderOneAccount = OrderSamples.MarketOrder("BUY", 100)
# Specify the Account Number directly
faOrderOneAccount.account = "DU119915"
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), faOrderOneAccount)
# ! [faorderoneaccount]
# ! [faordergroupequalquantity]
faOrderGroupEQ = OrderSamples.LimitOrder("SELL", 200, 2000)
faOrderGroupEQ.faGroup = "Group_Equal_Quantity"
faOrderGroupEQ.faMethod = "EqualQuantity"
self.placeOrder(self.nextOrderId(), ContractSamples.SimpleFuture(), faOrderGroupEQ)
# ! [faordergroupequalquantity]
# ! [faordergrouppctchange]
faOrderGroupPC = OrderSamples.MarketOrder("BUY", 0)
# You should not specify any order quantity for PctChange allocation method
faOrderGroupPC.faGroup = "Pct_Change"
faOrderGroupPC.faMethod = "PctChange"
faOrderGroupPC.faPercentage = "100"
self.placeOrder(self.nextOrderId(), ContractSamples.EurGbpFx(), faOrderGroupPC)
# ! [faordergrouppctchange]
# ! [faorderprofile]
faOrderProfile = OrderSamples.LimitOrder("BUY", 200, 100)
faOrderProfile.faProfile = "Percent_60_40"
self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), faOrderProfile)
# ! [faorderprofile]
# ! [modelorder]
modelOrder = OrderSamples.LimitOrder("BUY", 200, 100)
modelOrder.account = "DF12345"
modelOrder.modelCode = "Technology" # model for tech stocks first created in TWS
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), modelOrder)
# ! [modelorder]
self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(),
OrderSamples.Block("BUY", 50, 20))
self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(),
OrderSamples.BoxTop("SELL", 10))
self.placeOrder(self.nextOrderId(), ContractSamples.FutureComboContract(),
OrderSamples.ComboLimitOrder("SELL", 1, 1, False))
self.placeOrder(self.nextOrderId(), ContractSamples.StockComboContract(),
OrderSamples.ComboMarketOrder("BUY", 1, True))
self.placeOrder(self.nextOrderId(), ContractSamples.OptionComboContract(),
OrderSamples.ComboMarketOrder("BUY", 1, False))
self.placeOrder(self.nextOrderId(), ContractSamples.StockComboContract(),
OrderSamples.LimitOrderForComboWithLegPrices("BUY", 1, [10, 5], True))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.Discretionary("SELL", 1, 45, 0.5))
self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(),
OrderSamples.LimitIfTouched("BUY", 1, 30, 34))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.LimitOnClose("SELL", 1, 34))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.LimitOnOpen("BUY", 1, 35))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketIfTouched("BUY", 1, 30))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketOnClose("SELL", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketOnOpen("BUY", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketOrder("SELL", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketToLimit("BUY", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtIse(),
OrderSamples.MidpointMatch("BUY", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.MarketToLimit("BUY", 1))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.Stop("SELL", 1, 34.4))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.StopLimit("BUY", 1, 35, 33))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.StopWithProtection("SELL", 1, 45))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.SweepToFill("BUY", 1, 35))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.TrailingStop("SELL", 1, 0.5, 30))
self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
OrderSamples.TrailingStopLimit("BUY", 1, 2, 5, 50))
self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtIse(),
OrderSamples.Volatility("SELL", 1, 5, 2))
self.bracketSample()
self.conditionSamples()
self.hedgeSample()
# NOTE: the following orders are not supported for Paper Trading
# self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), OrderSamples.AtAuction("BUY", 100, 30.0))
# self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(), OrderSamples.AuctionLimit("SELL", 10, 30.0, 2))
# self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(), OrderSamples.AuctionPeggedToStock("BUY", 10, 30, 0.5))
# self.placeOrder(self.nextOrderId(), ContractSamples.OptionAtBOX(), OrderSamples.AuctionRelative("SELL", 10, 0.6))
# self.placeOrder(self.nextOrderId(), ContractSamples.SimpleFuture(), OrderSamples.MarketWithProtection("BUY", 1))
# self.placeOrder(self.nextOrderId(), ContractSamples.USStock(), OrderSamples.PassiveRelative("BUY", 1, 0.5))
# 208813720 (GOOG)
# self.placeOrder(self.nextOrderId(), ContractSamples.USStock(),
# OrderSamples.PeggedToBenchmark("SELL", 100, 33, True, 0.1, 1, 208813720, "ISLAND", 750, 650, 800))
# STOP ADJUSTABLE ORDERS
# Order stpParent = OrderSamples.Stop("SELL", 100, 30)
# stpParent.OrderId = self.nextOrderId()
# self.placeOrder(stpParent.OrderId, ContractSamples.EuropeanStock(), stpParent)
# self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), OrderSamples.AttachAdjustableToStop(stpParent, 35, 32, 33))
# self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), OrderSamples.AttachAdjustableToStopLimit(stpParent, 35, 33, 32, 33))
# self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), OrderSamples.AttachAdjustableToTrail(stpParent, 35, 32, 32, 1, 0))
# Order lmtParent = OrderSamples.LimitOrder("BUY", 100, 30)
# lmtParent.OrderId = self.nextOrderId()
# self.placeOrder(lmtParent.OrderId, ContractSamples.EuropeanStock(), lmtParent)
# Attached TRAIL adjusted can only be attached to LMT parent orders.
# self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), OrderSamples.AttachAdjustableToTrailAmount(lmtParent, 34, 32, 33, 0.008))
self.testAlgoSamples()
# Cancel all orders for all accounts ***/
# ! [reqglobalcancel]
self.reqGlobalCancel()
# ! [reqglobalcancel]
# Request the day's executions ***/
# ! [reqexecutions]
self.reqExecutions(10001, ExecutionFilter())
# ! [reqexecutions]
def orderOperations_cancel(self):
if self.simplePlaceOid is not None:
# ! [cancelorder]
self.cancelOrder(self.simplePlaceOid)
# ! [cancelorder]
def marketRuleOperations(self):
self.reqContractDetails(17001, ContractSamples.USStock())
self.reqContractDetails(17002, ContractSamples.Bond())
time.sleep(1)
# ! [reqmarketrule]
self.reqMarketRule(26)
self.reqMarketRule(240)
# ! [reqmarketrule]
@iswrapper
# ! [execdetails]
def execDetails(self, reqId: int, contract: Contract, execution: Execution):
super().execDetails(reqId, contract, execution)
print("ExecDetails. ", reqId, contract.symbol, contract.secType, contract.currency,
execution.execId, execution.orderId, execution.shares, execution.lastLiquidity)
# ! [execdetails]
@iswrapper
# ! [execdetailsend]
def execDetailsEnd(self, reqId: int):
super().execDetailsEnd(reqId)
print("ExecDetailsEnd. ", reqId)
# ! [execdetailsend]
@iswrapper
# ! [commissionreport]
def commissionReport(self, commissionReport: CommissionReport):
super().commissionReport(commissionReport)
print("CommissionReport. ", commissionReport.execId, commissionReport.commission,
commissionReport.currency, commissionReport.realizedPNL)
# ! [commissionreport]
def main():
SetupLogger()
logging.debug("now is %s", datetime.datetime.now())
logging.getLogger().setLevel(logging.ERROR)
cmdLineParser = argparse.ArgumentParser("api tests")
# cmdLineParser.add_option("-c", action="store_True", dest="use_cache", default = False, help = "use the cache")
# cmdLineParser.add_option("-f", action="store", type="string", dest="file", default="", help="the input file")
cmdLineParser.add_argument("-p", "--port", action="store", type=int,
dest="port", default=7497, help="The TCP port to use")
cmdLineParser.add_argument("-C", "--global-cancel", action="store_true",
dest="global_cancel", default=False,
help="whether to trigger a globalCancel req")
args = cmdLineParser.parse_args()
print("Using args", args)
logging.debug("Using args %s", args)
# print(args)
# enable logging when member vars are assigned
from ibapi import utils
from ibapi.order import Order
Order.__setattr__ = utils.setattr_log
from ibapi.contract import Contract, DeltaNeutralContract
Contract.__setattr__ = utils.setattr_log
DeltaNeutralContract.__setattr__ = utils.setattr_log
from ibapi.tag_value import TagValue
TagValue.__setattr__ = utils.setattr_log
TimeCondition.__setattr__ = utils.setattr_log
ExecutionCondition.__setattr__ = utils.setattr_log
MarginCondition.__setattr__ = utils.setattr_log
PriceCondition.__setattr__ = utils.setattr_log
PercentChangeCondition.__setattr__ = utils.setattr_log
VolumeCondition.__setattr__ = utils.setattr_log
# from inspect import signature as sig
# import code code.interact(local=dict(globals(), **locals()))
# sys.exit(1)
# tc = TestClient(None)
# tc.reqMktData(1101, ContractSamples.USStockAtSmart(), "", False, None)
# print(tc.reqId2nReq)
# sys.exit(1)
try:
app = TestApp()
if args.global_cancel:
app.globalCancelOnly = True
# ! [connect]
app.connect("127.0.0.1", args.port, clientId=0)
# ! [connect]
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
app.twsConnectionTime()))
# ! [clientrun]
app.run()
# ! [clientrun]
except:
raise
finally:
app.dumpTestCoverageSituation()
app.dumpReqAnsErrSituation()
if __name__ == "__main__":
main()
"""
Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
import sys
from ibapi.object_implem import Object
from ibapi.scanner import ScannerSubscription
class ScannerSubscriptionSamples(Object):
@staticmethod
def HotUSStkByVolume():
#! [hotusvolume]
#Hot US stocks by volume
scanSub = ScannerSubscription()
scanSub.instrument = "STK"
scanSub.locationCode = "STK.US.MAJOR"
scanSub.scanCode = "HOT_BY_VOLUME"
#! [hotusvolume]
return scanSub
@staticmethod
def TopPercentGainersIbis():
#! [toppercentgaineribis]
# Top % gainers at IBIS
scanSub = ScannerSubscription()
scanSub.instrument = "STOCK.EU"
scanSub.locationCode = "STK.EU.IBIS"
scanSub.scanCode = "TOP_PERC_GAIN"
#! [toppercentgaineribis]
return scanSub
@staticmethod
def MostActiveFutSoffex():
#! [mostactivefutsoffex]
# Most active futures at SOFFEX
scanSub = ScannerSubscription()
scanSub.instrument = "FUT.EU"
scanSub.locationCode = "FUT.EU.SOFFEX"
scanSub.scanCode = "MOST_ACTIVE"
#! [mostactivefutsoffex]
return scanSub
@staticmethod
def HighOptVolumePCRatioUSIndexes():
#! [highoptvolume]
# High option volume P/C ratio US indexes
scanSub = ScannerSubscription()
scanSub.instrument = "IND.US"
scanSub.locationCode = "IND.US"
scanSub.scanCode = "HIGH_OPT_VOLUME_PUT_CALL_RATIO"
#! [highoptvolume]
return scanSub
def Test():
print(ScannerSubscriptionSamples.HotUSStkByVolume())
print(ScannerSubscriptionSamples.TopPercentGainersIbis())
print(ScannerSubscriptionSamples.MostActiveFutSoffex())
print(ScannerSubscriptionSamples.HighOptVolumePCRatioUSIndexes())
if "__main__" == __name__:
Test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment