I got two questions:
- Why
get_position(context.security)
returnINFO: position: 0
, I just filled an order of 1 MES, it should be 1 instead? - Why did
close_all_positions()
fail to close my holding of 1 MES contract?
def initialize(context):
context.place_order=True
context.security = superSymbol(secType='FUT', symbol='MES', currency='USD', expiry='202509', exchange = 'CME')
def handle_data(context, data):
if context.place_order:
order_target(context.security, 1)
position = get_position(context.security)
log.info(f" position: {position.amount}")
close_all_positions()
context.place_order=False
end()
try:
log
except NameError:
class Logger:
def info(self, msg):
print(f"INFO: {msg}")
def warn(self, msg):
print(f"WARN: {msg}")
log = Logger()
On my TWS, I found 1 MES successfully bought, but failed to be closed by close_all_positions()
. On the other hand, i got the log on console as following:
Try to get connected to Interactive Brokers
Connected to Interactive Brokers
IBridgePy version 22.1.1
fileName = Quantra-IBridgePy\*************.py
#### Starting to initialize trader ####
## ACCOUNT Balance DU******* ##
CASH=999420.54
portfolio_value=999631.19
positions_value=0.0
## NO ANY POSITION ##
## NO any order ##
#### Initialize trader COMPLETED ####
INFO: position: 0
Try to get connected to Interactive Brokers
Quantra-IBridgePy\Place_and_Cancel_Orders\example_place_market_and_limit_order.py END