Python Forum

Full Version: Simple Python API, need packaging/removing hardcoding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, very much a newbie question, so pls go easy.

I have assembled the following program by searching the net - this basically logs onto a broker platform, via an API, and retrieves historical traded options data.

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

import threading
import time
from datetime import datetime, timedelta
import datetime

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def historicalData(self, reqId, bar):
        print ("Historical Data, ", reqId, " Date: ", bar.date, " Price: ", bar.close )
#        print(f'Time: {bar.date} .... Close: {bar.close}')


def run_loop():
    app.run()


app = IBapi()
app.connect('127.0.0.1', 7496, 123)

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

time.sleep(1)  # Sleep interval to allow time for connection to server

# Create contract object

contract = Contract()
contract.symbol = 'AAPL'
contract.secType = 'OPT'
contract.exchange = 'SMART'
contract.currency = 'USD'
[b]contract.lastTradeDateOrContractMonth = '20220610'
contract.symbol = 'AAPL'
contract.strike = 150
contract.right = 'C'[/b]
contract.multiplier = '100'

QueryTime = '20220609 17:50:00'

# Request historical candles
app.reqHistoricalData(1, contract, QueryTime, '18000 S', '10 mins', 'MIDPOINT', 0, 1, False, [])

time.sleep(5)  # sleep to allow enough time for data to be returned
app.disconnect()
***************
And this returns results like this :
Output:
Date: 20220608 20:50:00 Price: 0.765 Date: 20220609 14:30:00 Price: 0.455 Date: 20220609 14:40:00 Price: 0.525 Date: 20220609 14:50:00 Price: 0.645 Date: 20220609 15:00:00 Price: 0.405
However, as you can see, it contains hardcoded values in the following lines :
contract.lastTradeDateOrContractMonth = '20220610'
contract.symbol = 'AAPL'
contract.strike = 150
contract.right = 'C'
And what I would like is to package the whole program above so that it accepts 4 variables (lastTradeDateOrContractMonth , symbol, strike, right)
which I pass over. So, I'd like to issue a call like
run_program('20220610, 'AAPL', 150, 'C') and then this above program gets run and voila!

I cannot for the life of me do a simple thing like this.

PS, as you can tell my python is weaker than most peoples ability to speak Swahili,
or juggle 6 balls in the air. However, I'm keen to get this done, and I've even tried hiring people on upwork.com etc and have had 3 weeks of wasted effort, and money, and no result.

Can someone pls advice?
You can try this untested,i am using Typer here.
Do the first example it show main.py,so you know that Typer work.
Then from command line with code i have changed python run_program.py 20220610 AAPL 150 C
# run_program.py
import typer
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

import threading
import time
from datetime import datetime, timedelta
import datetime

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def historicalData(self, reqId, bar):
        print ("Historical Data, ", reqId, " Date: ", bar.date, " Price: ", bar.close )
        #print(f'Time: {bar.date} .... Close: {bar.close}')

def run_loop():
    app.run()

app = IBapi()
app.connect('127.0.0.1', 7496, 123)

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()
# Sleep interval to allow time for connection to server
time.sleep(1)


def run(last: str, symbol: str, strike: int, contract: str):
    contract = Contract()
    contract.symbol = 'AAPL'
    contract.secType = 'OPT'
    contract.exchange = 'SMART'
    contract.currency = 'USD'
    #
    contract.lastTradeDateOrContractMonth = last
    contract.symbol = symbol
    contract.strike = strike
    contract.right = contract
    #
    contract.multiplier = '100'
    QueryTime = '20220609 17:50:00'
    # Request historical candles
    app.reqHistoricalData(1, contract, QueryTime, '18000 S', '10 mins', 'MIDPOINT', 0, 1, False, [])
    # sleep to allow enough time for data to be returned
    time.sleep(5)
    app.disconnect()

if __name__ == "__main__":
    # Usage from  command line
    #python run_program.py 20220610 AAPL 150 C
    typer.run(run)
Thanks for the reply. I will try this. I'm getting a lot of errors, and am trying to get them resolved one at a time.