1 min read

IBKR API and TV Charts - Trendlines, Rays, and Supertrend

Downloading Price Data with Interactive Brokers API

from ib_insync import *
    
symbol = "MSFT"

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=13)
contract = Stock(symbol, 'SMART', 'USD')

bars = ib.reqHistoricalData(
        contract,
        endDateTime='',
        durationStr='3000 S',
        barSizeSetting='30 secs',
        whatToShow='TRADES',
        useRTH=True,
        formatDate=1)
        
df = util.df(bars)
df.to_csv(f"data/{symbol}.csv")

Downloading Price Data with the YFinance Package

import yfinance as yf
    
symbol = "NVDA"
ticker = yf.Ticker(symbol)
df = ticker.history(period="1y")

df.to_csv(f"data/{symbol}.csv")

Horizontal Lines and Trendlines on Interactive Brokers Price Data

import pandas as pd
from lightweight_charts import Chart

if __name__ == '__main__':
    chart = Chart(toolbox=True)

    df = pd.read_csv('data/AAPL.csv')
    df = df.set_index('date')
    df.index = pd.to_datetime(df.index, utc=True)

    chart.set(df)
    
    chart.watermark('AAPL')
    chart.horizontal_line(df['close'].max(), width=3, color='#FF0000')
    chart.horizontal_line(df['close'].min(), width=3, color='#00FF00')
    
    start_time = '2023-07-20 19:29:00'
    end_time = '2023-07-20 19:56:00'

    start_value = df[df.index == start_time]['close'].values[0]
    end_value = df[df.index == end_time]['close'].values[0]

    chart.trend_line(start_time, start_value, end_time, end_value, color='#0000FF', width=5)

    ray_line_start_time = '2023-07-20 19:21:00'
    ray_line_start_value = df[df.index == ray_line_start_time]['close'].values[0]

    chart.ray_line(ray_line_start_time, ray_line_start_value, color='#FF00FF')

    chart.show(block=True)

SuperTrend with TradingView Lightweight Charts and Pandas TA

import pandas as pd
import pandas_ta as ta
from lightweight_charts import Chart

if __name__ == '__main__':
    chart = Chart()

    df = pd.read_csv('data/AMD.csv')
    df = df.set_index('Date')
    df.index = pd.to_datetime(df.index, utc=True)

    supertrend = df.ta.supertrend(length=10, multiplier=3)
    supertrend = supertrend.reset_index()

    print(supertrend)
    supertrend_short = pd.DataFrame()
    supertrend_long = pd.DataFrame()

    supertrend_long['time'] = supertrend['Date']
    supertrend_long['value'] = supertrend['SUPERTl_10_3.0']
    supertrend_long = supertrend_long.dropna()

    supertrend_short['time'] = supertrend['Date']
    supertrend_short['value'] = supertrend['SUPERTs_10_3.0']
    supertrend_short = supertrend_short.dropna()

    chart.set(df)

    long_line = chart.create_line(color='rgba(0, 255, 0, 1)')    
    long_line.set(supertrend_long)
    
    short_line = chart.create_line(color='rgba(255, 0, 0, 1)')
    short_line.set(supertrend_short)
    
    chart.show(block=True)

Exporting Positions to CSV with Interactive Brokers API

import csv
from ib_insync import *

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=3)

with open('positions.csv', 'w') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerow(['symbol', 'quantity', 'avg cost'])

    for position in ib.positions():   
        writer.writerow([position.contract.symbol, position.position, position.avgCost])