fix Order api function calls in the script based on this documentation : [docs]

class LimitOrder(Order):

 

    def __init__(self, action: str, totalQuantity: float, lmtPrice: float,

                 **kwargs):

        Order.__init__(

            self, orderType='LMT', action=action,

            totalQuantity=totalQuantity, lmtPrice=lmtPrice, **kwargs)

 

 

 

 

 

[docs]

class MarketOrder(Order):

 

    def __init__(self, action: str, totalQuantity: float, **kwargs):

        Order.__init__(

            self, orderType='MKT', action=action,

            totalQuantity=totalQuantity, **kwargs)

 

 

 

 

 

[docs]

class StopOrder(Order):

 

    def __init__(self, action: str, totalQuantity: float, stopPrice: float,

                 **kwargs):

        Order.__init__(

            self, orderType='STP', action=action,

            totalQuantity=totalQuantity, auxPrice=stopPrice, **kwargs)

 

 

[docs]

    def cancelOrder(self, orderId, manualCancelOrderTime=''):

        fields = [4, 1, orderId]

        if self.serverVersion() >= 169:

            fields += [manualCancelOrderTime]

        self.send(*fields)

 

 

 

 

[docs]

    def reqOpenOrders(self):

        self.send(5, 1)

 

 

 

 

[docs]

    def reqAccountUpdates(self, subscribe, acctCode):

        self.send(6, 2, subscribe, acctCode)

 

 

 

 

[docs]

    def reqExecutions(self, reqId, execFilter):

        self.send(

            7, 3, reqId,

            execFilter.clientId,

            execFilter.acctCode,

            execFilter.time,

            execFilter.symbol,

            execFilter.secType,

            execFilter.exchange,

            execFilter.side)

 

 

 

 

[docs]

    def reqIds(self, numIds):

        self.send(8, 1, numIds)

 

 

 

 

[docs]

    def reqContractDetails(self, reqId, contract):

        fields = [

            9, 8, reqId,

            contract,

            contract.includeExpired,

            contract.secIdType,

            contract.secId]

        if self.serverVersion() >= 176:

            fields += [contract.issuerId]

        self.send(*fields)

 

 

 

 

[docs]

    def reqMktDepth(

            self, reqId, contract, numRows, isSmartDepth, mktDepthOptions):

        self.send(

            10, 5, reqId,

            contract.conId,

            contract.symbol,

            contract.secType,

            contract.lastTradeDateOrContractMonth,

            contract.strike,

            contract.right,

            contract.multiplier,

            contract.exchange,

            contract.primaryExchange,

            contract.currency,

            contract.localSymbol,

            contract.tradingClass,

            numRows,

            isSmartDepth,

            mktDepthOptions)

 

 

 

 

[docs]

    def cancelMktDepth(self, reqId, isSmartDepth):

        self.send(11, 1, reqId, isSmartDepth)

 

 

 

 

[docs]

    def reqNewsBulletins(self, allMsgs):

        self.send(12, 1, allMsgs)

 

 

 

 

[docs]

    def cancelNewsBulletins(self):

        self.send(13, 1)

 

 

 

 

[docs]

    def setServerLogLevel(self, logLevel):

        self.send(14, 1, logLevel)

 

 

 

 

[docs]

    def reqAutoOpenOrders(self, bAutoBind):

        self.send(15, 1, bAutoBind)

 

 

 

 

[docs]

    def reqAllOpenOrders(self):

        self.send(16, 1)

 

 

 

 

[docs]

    def reqManagedAccts(self):

        self.send(17, 1)

 

 

 

 

[docs]

    def requestFA(self, faData):

        self.send(18, 1, faData)

 

 

 

 

[docs]

    def replaceFA(self, reqId, faData, cxml):

        self.send(19, 1, faData, cxml, reqId)

 

 

 

 

[docs]

    def reqHistoricalData(

            self, reqId, contract, endDateTime, durationStr, barSizeSetting,

            whatToShow, useRTH, formatDate, keepUpToDate, chartOptions):

        fields = [

            20, reqId, contract, contract.includeExpired,

            endDateTime, barSizeSetting, durationStr, useRTH,

            whatToShow, formatDate]

 

        if contract.secType == 'BAG':

            legs = contract.comboLegs or []

            fields += [len(legs)]

            for leg in legs:

                fields += [leg.conId, leg.ratio, leg.action, leg.exchange]

 

        fields += [keepUpToDate, chartOptions]

        self.send(*fields)

 

 

 

 

[docs]

    def exerciseOptions(

            self, reqId, contract, exerciseAction,

            exerciseQuantity, account, override):

        self.send(

            21, 2, reqId,

            contract.conId,

            contract.symbol,

            contract.secType,

            contract.lastTradeDateOrContractMonth,

            contract.strike,

            contract.right,

            contract.multiplier,

            contract.exchange,

            contract.currency,

            contract.localSymbol,

            contract.tradingClass,

            exerciseAction, exerciseQuantity, account, override)

 

 

 

 

[docs]

    def reqScannerSubscription(

            self, reqId, subscription, scannerSubscriptionOptions,

            scannerSubscriptionFilterOptions):

        sub = subscription

        self.send(

            22, reqId,

            sub.numberOfRows,

            sub.instrument,

            sub.locationCode,

            sub.scanCode,

            sub.abovePrice,

            sub.belowPrice,

            sub.aboveVolume,

            sub.marketCapAbove,

            sub.marketCapBelow,

            sub.moodyRatingAbove,

            sub.moodyRatingBelow,

            sub.spRatingAbove,

            sub.spRatingBelow,

            sub.maturityDateAbove,

            sub.maturityDateBelow,

            sub.couponRateAbove,

            sub.couponRateBelow,

            sub.excludeConvertible,

            sub.averageOptionVolumeAbove,

            sub.scannerSettingPairs,

            sub.stockTypeFilter,

            scannerSubscriptionFilterOptions,

            scannerSubscriptionOptions)

 

 

 

 

[docs]

    def cancelScannerSubscription(self, reqId):

        self.send(23, 1, reqId)

 

 

 

 

[docs]

    def reqScannerParameters(self):

        self.send(24, 1)

 

 

 

 

[docs]

    def cancelHistoricalData(self, reqId):

        self.send(25, 1, reqId)

 

 

 

 

[docs]

    def reqCurrentTime(self):

        self.send(49, 1)

 

 

 

 

[docs]

    def reqRealTimeBars(

            self, reqId, contract, barSize, whatToShow,

            useRTH, realTimeBarsOptions):

        self.send(

            50, 3, reqId, contract, barSize, whatToShow,

            useRTH, realTimeBarsOptions)

 

 

 

 

[docs]

    def cancelRealTimeBars(self, reqId):

        self.send(51, 1, reqId)

 

 

 

 

[docs]

    def reqFundamentalData(

            self, reqId, contract, reportType, fundamentalDataOptions):

        options = fundamentalDataOptions or []

        self.send(

            52, 2, reqId,

            contract.conId,

            contract.symbol,

            contract.secType,

            contract.exchange,

            contract.primaryExchange,

            contract.currency,

            contract.localSymbol,

            reportType, len(options), options)

 

 

 

 

[docs]

    def cancelFundamentalData(self, reqId):

        self.send(53, 1, reqId)

 

 

 

 

[docs]

    def calculateImpliedVolatility(

            self, reqId, contract, optionPrice, underPrice, implVolOptions):

        self.send(

            54, 3, reqId, contract, optionPrice, underPrice,

            len(implVolOptions), implVolOptions)

 
 

 
 

 class StopLimitOrder(Order):

 

    def __init__(self, action: str, totalQuantity: float, lmtPrice: float,

                 stopPrice: float, **kwargs):

        Order.__init__(

            self, orderType='STP LMT', action=action,

            totalQuantity=totalQuantity, lmtPrice=lmtPrice,

            auxPrice=stopPrice, **kwargs)

 

 def bracketOrder(

            self, action: str, quantity: float,

            limitPrice: float, takeProfitPrice: float,

            stopLossPrice: float, **kwargs) -> BracketOrder:

        """

        Create a limit order that is bracketed by a take-profit order and

        a stop-loss order. Submit the bracket like:

 

        .. code-block:: python

 

            for o in bracket:

                ib.placeOrder(contract, o)

 

        https://interactivebrokers.github.io/tws-api/bracket_order.html

 

        Args:

            action: 'BUY' or 'SELL'.

            quantity: Size of order.

            limitPrice: Limit price of entry order.

            takeProfitPrice: Limit price of profit order.

            stopLossPrice: Stop price of loss order.

        """

        assert action in ('BUY', 'SELL')

        reverseAction = 'BUY' if action == 'SELL' else 'SELL'

        parent = LimitOrder(

            action, quantity, limitPrice,

            orderId=self.client.getReqId(),

            transmit=False,

            **kwargs)

        takeProfit = LimitOrder(

            reverseAction, quantity, takeProfitPrice,

            orderId=self.client.getReqId(),

            transmit=False,

            parentId=parent.orderId,

            **kwargs)

        stopLoss = StopOrder(

            reverseAction, quantity, stopLossPrice,

            orderId=self.client.getReqId(),

            transmit=True,

            parentId=parent.orderId,

            **kwargs)

        return BracketOrder(parent, takeProfit, stopLoss)

 

 

 

 

[docs]

    @staticmethod

    def oneCancelsAll(

            orders: List[Order], ocaGroup: str, ocaType: int) -> List[Order]:

        """

        Place the trades in the same One Cancels All (OCA) group.

 

        https://interactivebrokers.github.io/tws-api/oca.html

 

        Args:

            orders: The orders that are to be placed together.

        """

        for o in orders:

            o.ocaGroup = ocaGroup

            o.ocaType = ocaType

        return orders

 

 

 

 

[docs]

    def whatIfOrder(self, contract: Contract, order: Order) -> OrderState:

        """

        Retrieve commission and margin impact without actually

        placing the order. The given order will not be modified in any way.

 

        This method is blocking.

 

        Args:

            contract: Contract to test.

            order: Order to test.

        """

        return self._run(self.whatIfOrderAsync(contract, order))

 

 

 

 

[docs]

    def placeOrder(self, contract: Contract, order: Order) -> Trade:

        """

        Place a new order or modify an existing order.

        Returns a Trade that is kept live updated with

        status changes, fills, etc.

 

        Args:

            contract: Contract to use for order.

            order: The order to be placed.

        """

        orderId = order.orderId or self.client.getReqId()

        self.client.placeOrder(orderId, contract, order)

        now = datetime.datetime.now(datetime.timezone.utc)

        key = self.wrapper.orderKey(

            self.wrapper.clientId, orderId, order.permId)

        trade = self.wrapper.trades.get(key)

        if trade:

            # this is a modification of an existing order

            assert trade.orderStatus.status not in OrderStatus.DoneStates

            logEntry = TradeLogEntry(now, trade.orderStatus.status, 'Modify')

            trade.log.append(logEntry)

            self._logger.info(f'placeOrder: Modify order {trade}')

            trade.modifyEvent.emit(trade)

            self.orderModifyEvent.emit(trade)

        else:

            # this is a new order

            order.clientId = self.wrapper.clientId

            order.orderId = orderId

            orderStatus = OrderStatus(

                orderId=orderId, status=OrderStatus.PendingSubmit)

            logEntry = TradeLogEntry(now, orderStatus.status)

            trade = Trade(contract, order, orderStatus, [], [logEntry])

            self.wrapper.trades[key] = trade

            self._logger.info(f'placeOrder: New order {trade}')

            self.newOrderEvent.emit(trade)

        return trade

 

 

 

 

[docs]

    def cancelOrder(self, order: Order, manualCancelOrderTime: str = '') \

            -> Optional[Trade]:

        """

        Cancel the order and return the Trade it belongs to.

 

        Args:

            order: The order to be canceled.

            manualCancelOrderTime: For audit trail.

        """

        self.client.cancelOrder(order.orderId, manualCancelOrderTime)

        now = datetime.datetime.now(datetime.timezone.utc)

        key = self.wrapper.orderKey(

            order.clientId, order.orderId, order.permId)

        trade = self.wrapper.trades.get(key)

        if trade:

            if not trade.isDone():

                status = trade.orderStatus.status

                if (status == OrderStatus.PendingSubmit and not order.transmit

                        or status == OrderStatus.Inactive):

                    newStatus = OrderStatus.Cancelled

                else:

                    newStatus = OrderStatus.PendingCancel

                logEntry = TradeLogEntry(now, newStatus)

                trade.log.append(logEntry)

                trade.orderStatus.status = newStatus

                self._logger.info(f'cancelOrder: {trade}')

                trade.cancelEvent.emit(trade)

                trade.statusEvent.emit(trade)

                self.cancelOrderEvent.emit(trade)

                self.orderStatusEvent.emit(trade)

                if newStatus == OrderStatus.Cancelled:

                    trade.cancelledEvent.emit(trade)

        else:

            self._logger.error(f'cancelOrder: Unknown orderId {order.orderId}')

        return trade

  def openOrder(

            self, orderId: int, contract: Contract, order: Order,

            orderState: OrderState):

        """

        This wrapper is called to:

 

        * feed in open orders at startup;

        * feed in open orders or order updates from other clients and TWS

          if clientId=master id;

        * feed in manual orders and order updates from TWS if clientId=0;

        * handle openOrders and allOpenOrders responses.

        """

        if order.whatIf:

            # response to whatIfOrder

            if orderState.initMarginChange != str(UNSET_DOUBLE):

                self._endReq(order.orderId, orderState)

        else:

            key = self.orderKey(order.clientId, order.orderId, order.permId)

            trade = self.trades.get(key)

            if trade:

                trade.order.permId = order.permId

                trade.order.totalQuantity = order.totalQuantity

                trade.order.lmtPrice = order.lmtPrice

                trade.order.auxPrice = order.auxPrice

                trade.order.orderType = order.orderType

                trade.order.orderRef = order.orderRef

            else:

                # ignore '?' values in the order

                order = Order(**{

                    k: v for k, v in dataclassAsDict(order).items()

                    if v != '?'})

                contract = Contract.create(**dataclassAsDict(contract))

                orderStatus = OrderStatus(

                    orderId=orderId, status=orderState.status)

                trade = Trade(contract, order, orderStatus, [], [])

                self.trades[key] = trade

                self._logger.info(f'openOrder: {trade}')

            self.permId2Trade.setdefault(order.permId, trade)

            results = self._results.get('openOrders')

            if results is None:

                self.ib.openOrderEvent.emit(trade)

            else:

                # response to reqOpenOrders or reqAllOpenOrders

                results.append(trade)

 

        # make sure that the client issues order ids larger than any

        # order id encountered (even from other clients) to avoid

        # "Duplicate order id" error

        self.ib.client.updateReqId(orderId + 1)

 

    def openOrderEnd(self):

        self._endReq('openOrders')

 

    def completedOrder(

            self, contract: Contract, order: Order, orderState: OrderState):

        contract = Contract.create(**dataclassAsDict(contract))

        orderStatus = OrderStatus(

            orderId=order.orderId, status=orderState.status)

        trade = Trade(contract, order, orderStatus, [], [])

        self._results['completedOrders'].append(trade)

        if order.permId not in self.permId2Trade:

            self.trades[order.permId] = trade

            self.permId2Trade[order.permId] = trade

 

    def completedOrdersEnd(self):

        self._endReq('completedOrders')

 

    def orderStatus(

            self, orderId: int, status: str, filled: float, remaining: float,

            avgFillPrice: float, permId: int, parentId: int,

            lastFillPrice: float, clientId: int, whyHeld: str,

            mktCapPrice: float = 0.0):

        key = self.orderKey(clientId, orderId, permId)

        trade = self.trades.get(key)

        if trade:

            msg: Optional[str]

            oldStatus = trade.orderStatus.status

            new = dict(

                status=status, filled=filled,

                remaining=remaining, avgFillPrice=avgFillPrice,

                permId=permId, parentId=parentId,

                lastFillPrice=lastFillPrice, clientId=clientId,

                whyHeld=whyHeld, mktCapPrice=mktCapPrice)

            curr = dataclassAsDict(trade.orderStatus)

            isChanged = curr != {**curr, **new}

            if isChanged:

                dataclassUpdate(trade.orderStatus, **new)

                msg = ''

            elif (status == 'Submitted' and trade.log

                    and trade.log[-1].message == 'Modify'):

                # order modifications are acknowledged

                msg = 'Modified'

            else:

                msg = None

 

            if msg is not None:

                logEntry = TradeLogEntry(self.lastTime, status, msg)

                trade.log.append(logEntry)

                self._logger.info(f'orderStatus: {trade}')

                self.ib.orderStatusEvent.emit(trade)

                trade.statusEvent.emit(trade)

                if status != oldStatus:

                    if status == OrderStatus.Filled:

                        trade.filledEvent.emit(trade)

                    elif status == OrderStatus.Cancelled:

                        trade.cancelledEvent.emit(trade)

        else:

            self._logger.error(

                'orderStatus: No order found for '

                'orderId %s and clientId %s', orderId, clientId)

 MY CODE TO FIX: # trading_bot.py

import pandas as pd
from ib_insync import *
import time
import csv
from datetime import datetime

# Initialize the IB connection
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)  # Adjust the port and clientId if necessary

# Read the CSV file
def read_daily_entries(csv_file):
    entries_df = pd.read_csv(csv_file)

    # Convert percentage strings to float
    entries_df['ManualStopLossAdjustment'] = entries_df['ManualStopLossAdjustment'].str.rstrip('%').astype('float') / 100.0
    entries_df['EntryPriceRangePercentage1'] = entries_df['EntryPriceRangePercentage1'].str.rstrip('%').astype('float') / 100.0
    entries_df['EntryPriceRangePercentage2'] = entries_df['EntryPriceRangePercentage2'].str.rstrip('%').astype('float') / 100.0
    entries_df['TakeProfitSharePercentage'] = entries_df['TakeProfitSharePercentage'].str.rstrip('%').astype('float') / 100.0

    return entries_df

# Get previous day's high or low
def get_previous_day_price(symbol, price_type):
    # Adjust the contract according to the instrument (e.g., use Index, Stock, Future)
    contract = Index(symbol, 'CBOE')  # Update this as needed
    ib.qualifyContracts(contract)

    # Request historical data
    bars = ib.reqHistoricalData(
        contract,
        endDateTime='',
        durationStr='2 D',
        barSizeSetting='1 day',
        whatToShow='TRADES',
        useRTH=True,
        formatDate=1
    )

    if len(bars) >= 2:
        prev_day_bar = bars[-2]
        if price_type == 'high':
            return prev_day_bar.high
        elif price_type == 'low':
            return prev_day_bar.low
    else:
        return None

# Place conditional orders
def place_order(row):
    symbol = row['Ticker']
    position_type = row['PositionType']
    entry_price1 = row['EntryPrice1']
    quantity = int(row['Quantity'])
    account = str(row['IBAccount'])
    entry_type_hours = row['EntryTypeHours']
    entry_tif = row['EntryTimeInForce']

    # Create contract
    contract = Index(symbol, 'CBOE')
    ib.qualifyContracts(contract)

    # Determine action
    if position_type.lower() == 'long':
        action = 'BUY'
    else:
        action = 'SELL'

    # Determine whether to allow trading outside RTH
    if entry_type_hours.lower() == 'rth':
        # Regular Trading Hours only
        outside_rth = False
    else:
        # Include Extended Trading Hours
        outside_rth = True

    # Create limit order with conditional entry price
    entry_order = LimitOrder(action, quantity, entry_price1, account=account, tif=entry_tif, outsideRth=outside_rth)
    trade = ib.placeOrder(contract, entry_order)

    print(f"Placed {position_type} order for {symbol}: {quantity} contracts at ${entry_price1:.2f}, Outside RTH: {outside_rth}")

    return trade, contract

# Profit management
def profit_management(trade, contract, row):
    # Wait for order to fill
    while trade.orderStatus.status != 'Filled':
        ib.sleep(1)

    filled_price = trade.orderStatus.avgFillPrice
    quantity = trade.orderStatus.filled
    position_type = row['PositionType']
    take_profit_exit = row['TakeProfitSharePercentage']
    manual_stop_loss_adj = row['ManualStopLossAdjustment']
    risk_per_unit = row['RiskPerUnit']
    account = str(row['IBAccount'])
    stop_loss_hours = row['StopLossHours']
    take_profit_hours = row['TakeProfitHours']

    print(f"Order filled at ${filled_price:.2f} for {quantity} contracts.")

    # Calculate risk and stop loss price
    if position_type.lower() == 'long':
        initial_stop_loss = float(row['InitialStopLoss'])
        risk = filled_price - initial_stop_loss
        stop_loss_price = filled_price - (manual_stop_loss_adj * risk)
        stop_action = 'SELL'
        tp_action = 'SELL'
    else:
        initial_stop_loss = float(row['InitialStopLoss'])
        risk = initial_stop_loss - filled_price
        stop_loss_price = filled_price + (manual_stop_loss_adj * risk)
        stop_action = 'BUY'
        tp_action = 'BUY'

    # Determine whether to allow trading outside RTH for Stop Loss
    if stop_loss_hours.lower() == 'rth':
        sl_outside_rth = False
    else:
        sl_outside_rth = True

    # Create Stop Loss Order
    sl_order = StopOrder(stop_action, quantity, stop_loss_price, account=account, outsideRth=sl_outside_rth)
    ib.placeOrder(contract, sl_order)

    print(f"Placed Stop Loss order at ${stop_loss_price:.2f}, Outside RTH: {sl_outside_rth}")

    # Take Profit logic
    take_profit_quantity = int(quantity * take_profit_exit)
    if position_type.lower() == 'long':
        take_profit_price = filled_price + risk
    else:
        take_profit_price = filled_price - risk

    # Determine whether to allow trading outside RTH for Take Profit
    if take_profit_hours.lower() == 'rth':
        tp_outside_rth = False
    else:
        tp_outside_rth = True

    tp_order = LimitOrder(tp_action, take_profit_quantity, take_profit_price, account=account, outsideRth=tp_outside_rth)
    ib.placeOrder(contract, tp_order)

    print(f"Placed Take Profit order at ${take_profit_price:.2f} for {take_profit_quantity} contracts, Outside RTH: {tp_outside_rth}")

    # Monitor for TP or SL hit
    monitor_trade(contract, position_type, filled_price, stop_loss_price, take_profit_price, quantity, take_profit_quantity, account)

# Monitoring the trade
def monitor_trade(contract, position_type, entry_price, stop_loss_price, take_profit_price, total_quantity, tp_quantity, account):
    position_closed = False
    while not position_closed:
        ib.sleep(5)
        market_data = ib.reqMktData(contract, '', False, False)
        ib.sleep(1)  # Allow time for market data to be received
        market_price = market_data.last

        if market_price is None:
            continue

        if position_type.lower() == 'long':
            if market_price <= stop_loss_price:
                print(f"Stop Loss hit at ${market_price:.2f}. Closing position.")
                close_position(contract, 'SELL', total_quantity, account)
                position_closed = True
            elif market_price >= take_profit_price:
                print(f"Take Profit target reached at ${market_price:.2f}.")
                # Create trailing stop for remaining position
                remaining_quantity = total_quantity - tp_quantity
                if remaining_quantity > 0:
                    create_trailing_stop(contract, 'SELL', remaining_quantity, account)
                position_closed = True
        else:
            if market_price >= stop_loss_price:
                print(f"Stop Loss hit at ${market_price:.2f}. Closing position.")
                close_position(contract, 'BUY', total_quantity, account)
                position_closed = True
            elif market_price <= take_profit_price:
                print(f"Take Profit target reached at ${market_price:.2f}.")
                # Create trailing stop for remaining position
                remaining_quantity = total_quantity - tp_quantity
                if remaining_quantity > 0:
                    create_trailing_stop(contract, 'BUY', remaining_quantity, account)
                position_closed = True

# Create trailing stop for remaining position
def create_trailing_stop(contract, action, quantity, account):
    # Implement logic for manual adjustment or trailing stop
    print(f"Creating trailing stop for {quantity} contracts.")
    # For simplicity, use a trailing amount (e.g., $10)
    trailing_amount = 10.0
    ts_order = TrailStopOrder(action, quantity, trailingAmount=trailing_amount, account=account)
    ib.placeOrder(contract, ts_order)

    print(f"Placed trailing stop order with trailing amount ${trailing_amount:.2f}.")

# Close position
def close_position(contract, action, quantity, account):
    close_order = MarketOrder(action, quantity, account=account)
    ib.placeOrder(contract, close_order)

# Record trade
def record_trade(symbol, entry_price, exit_price, quantity, entry_date, exit_date, profit_loss, commissions):
    trade_record = {
        'Symbol': symbol,
        'EntryPrice': entry_price,
        'ExitPrice': exit_price,
        'Quantity': quantity,
        'EntryDate': entry_date,
        'ExitDate': exit_date,
        'ProfitLoss': profit_loss,
        'Commissions': commissions
    }

    # Append to CSV
    with open('trade_records.csv', 'a', newline='') as csvfile:
        fieldnames = ['Symbol', 'EntryPrice', 'ExitPrice', 'Quantity', 'EntryDate', 'ExitDate', 'ProfitLoss', 'Commissions']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow(trade_record)

    print(f"Recorded trade for {symbol}.")

# Main function
def main():
    # Read the CSV file
    entries_df = read_daily_entries('daily_entries.csv')

    # Process each entry
    for index, row in entries_df.iterrows():
        symbol = row['Ticker'] #4
        position_type = row['PositionType'] #5
        initial_stop_loss = float(row['InitialStopLoss']) #6
        risk_amount = float(row['RiskAmount'])#1
        entry_percentage1 = float(row['EntryPriceRangePercentage1']) #2
        entry_percentage2 = float(row['EntryPriceRangePercentage2']) #3
        take_profit_share_percentage = row['TakeProfitSharePercentage'] #7
        manual_stop_loss_adj = row['ManualStopLossAdjustment'] #8
        ib_account = str(row['IBAccount'])
        entry_time_in_force = row['EntryTimeInForce']
        entry_type_hours = row['EntryTypeHours']
        stop_loss_hours = row['StopLossHours']
        take_profit_hours = row['TakeProfitHours']

        # Get previous day's high or low
        if position_type.lower() == 'long':
            prev_price = get_previous_day_price(symbol, 'high') #9
        else:
            prev_price = get_previous_day_price(symbol, 'low') #9

        if prev_price is None:
            print(f"Couldn't retrieve previous day's price for {symbol}.")
            continue

        # Calculate risk per unit
        if position_type.lower() == 'long':
            risk_per_unit = prev_price - initial_stop_loss #[10]
            entry_price1 = (entry_percentage1 * risk_per_unit) + prev_price #11
            entry_price2 = (entry_percentage2 * risk_per_unit) + prev_price #12
        else:
            risk_per_unit = initial_stop_loss - prev_price
            entry_price1 = prev_price - (entry_percentage1 * risk_per_unit)
            entry_price2 = prev_price - (entry_percentage2 * risk_per_unit)

        # Calculate quantity
        quantity = int(risk_amount / risk_per_unit) #13

        # Update the DataFrame
        entries_df.at[index, 'RiskPerUnit'] = risk_per_unit
        entries_df.at[index, 'EntryPrice1'] = entry_price1
        entries_df.at[index, 'EntryPrice2'] = entry_price2
        entries_df.at[index, 'Quantity'] = quantity
        entries_df.at[index, 'TakeProfitSharePercentage'] = take_profit_share_percentage
        entries_df.at[index, 'ManualStopLossAdjustment'] = manual_stop_loss_adj
        entries_df.at[index, 'IBAccount'] = ib_account
        entries_df.at[index, 'EntryTypeHours'] = entry_type_hours
        entries_df.at[index, 'StopLossHours'] = stop_loss_hours
        entries_df.at[index, 'TakeProfitHours'] = take_profit_hours

        # Place order and manage trade
        trade, contract = place_order(entries_df.loc[index])
        profit_management(trade, contract, entries_df.loc[index])

    ib.disconnect()

if __name__ == "__main__":
    main() FOCUS ON COMLPYING PERFECTLY TO THE API