예제 #1
0
def get_contract_details(client):
    ''' Define the contract of intrest'''
    # pdb.set_trace()
    contract = Contract()
    contract.symbol = 'NIFTY50'
    contract.secType = "CONTFUT"
    contract.exchange = 'NSE'
    contract.primaryExchange = 'NSE'
    contract.currency = "INR"
    contract.includeExpired = True

    # Get complete details about the contract from IB's database
    client.contractDetailsEnd_available.clear(
    )  # internal flag is set to False
    client.reqContractDetails(1, contract)
    client.contractDetailsEnd_available.wait(
    )  # block thread until internal flag is set to True

    if client.local_symbol:
        print('Local Symbol : {}'.format(client.local_symbol))
        # Set additional contract data
        contract.localSymbol = client.local_symbol
        contract.multiplier = client.multiplier
    else:
        print('Could not access contract data From reqContractDetails')
        exit_program(client)

    return contract
예제 #2
0
def main():

    # Create the client and connect to TWS
    client = ReadFutures('127.0.0.1', 7497, 0)

    # Get expiration dates for contracts
    for symbol in client.symbols:

        # Define contract of interest
        con = Contract()
        con.symbol = symbol
        con.secType = "CONTFUT"
        con.exchange = client.symbols[symbol]
        con.currency = "USD"
        con.includeExpired = True
        client.reqContractDetails(0, con)
        time.sleep(3)

        # Request historical data for each contract
        if client.local_symbol:

            # Initialize price dict
            for v in ['CLOSE', 'LOW', 'HIGH', 'VOL']:
                client.price_dict[v] = []

            # Set additional contract data
            con.localSymbol = client.local_symbol
            con.multiplier = client.multiplier

            # Request historical data
            end_date = datetime.today().date() - timedelta(days=1)
            client.reqHistoricalData(1, con,
                                     end_date.strftime("%Y%m%d %H:%M:%S"),
                                     '1 Y', '1 day', 'TRADES', 1, 1, False, [])
            time.sleep(3)

            # Write data to a CSV file
            if client.price_dict['CLOSE']:
                df = pd.DataFrame(data=client.price_dict)
                df.to_csv(symbol + '.csv', encoding='utf-8', index=False)
                client.price_dict.clear()
        else:
            print('Could not access contract data')
            exit()

    # Disconnect from TWS
    client.disconnect()
def main():
    # Create the client and connect to TWS
    client = WriteFuturesToCSV('127.0.0.1', 7497, 0)
    client.nextValidId_available.wait(
    )  # block thread until internal flag is set to True

    print('\n   Good to Go Baba. We are Connected to TWS')
    print('   The Order Id is: {}'.format(client.orderId))
    print('   The Account Details are: {}\n'.format(client.accountsList))

    # Get expiration dates for contracts
    for count, symbol in enumerate(client.symbols):
        # Define contract of interest
        contract = Contract()
        contract.symbol = symbol
        contract.secType = "CONTFUT"
        contract.exchange = client.symbols[symbol]
        contract.primaryExchange = client.symbols[symbol]
        contract.currency = "INR"
        contract.includeExpired = True

        client.contractDetailsEnd_available.clear(
        )  #internal flag is set to False
        client.reqContractDetails(count, contract)
        client.contractDetailsEnd_available.wait(
        )  # block thread until internal flag is set to True

        # Request historical data for each contract
        if client.local_symbol:
            print('Local Symbol : {}'.format(client.local_symbol))
            print('Symbol : {}'.format(symbol))

            # Set additional contract data
            contract.localSymbol = client.local_symbol
            contract.multiplier = client.multiplier

            # Initialize the deque
            client.date_dq.clear()
            client.open_dq.clear()
            client.high_dq.clear()
            client.low_dq.clear()
            client.close_dq.clear()
            client.volume_dq.clear()

            client.historicalDataEnd_available.clear(
            )  #internal flag is set to False

            # Request historical data
            query_time = (datetime.today().date() -
                          timedelta(days=0)).strftime("%Y%m%d %H:%M:%S")
            client.reqHistoricalData(count, contract, query_time, '2 Y',
                                     '1 day', 'TRADES', 1, 1, False, [])
            client.historicalDataEnd_available.wait(
            )  # block thread until internal flag is set to True

            #  Create List
            date_list = list(client.date_dq)
            open_list = list(client.open_dq)
            high_list = list(client.high_dq)
            low_list = list(client.low_dq)
            close_list = list(client.close_dq)
            volume_list = list(client.volume_dq)
            combined_list = [
                date_list, open_list, high_list, low_list, close_list,
                volume_list
            ]

            # Write data to a CSV file
            df = pd.DataFrame(combined_list).transpose()
            df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
            df['Date'] = pd.to_datetime(
                df['Date'])  # Convert to pandas DateTime format
            df = df[df.Volume !=
                    0]  # Drop all entries for which volume traded = 0
            df.to_csv(client.local_symbol + '.csv',
                      encoding='utf-8',
                      index=False)

            combined_list = []  # Empty the List
        else:
            print('Could not access contract data')
            sys.exit()

    # Disconnect from TWS. But first cancel open Subscriptions
    client.cancelHistoricalData(count)  # provide ID of original request
    client.disconnect()
예제 #4
0
def close_open_position(client, action: str, quantity: int):
    quantity = int(quantity)
    print('Entered Close Position')
    # Define the futures Contract prior to placing order
    contract = Contract()
    contract.localSymbol = client.local_symbol
    contract.secType = 'FUT'
    contract.exchange = 'NSE'
    contract.currency = 'INR'
    contract.primaryExchange = "NSE"

    # Define the Limit Order for BUY/SELL
    order = Order()
    order.action = action
    order.totalQuantity = quantity
    order.orderType = 'MKT'

    # Request from TWS, the next valid ID for the order.
    client.nextValidId_available.clear()  # internal flag is set to False
    client.reqIds(-1)  # The parameter is always ignored.
    client.nextValidId_available.wait(
    )  # block thread until internal flag is set to True

    # Place the order
    if client.orderId:
        # for Market Orders use execDetails callback instead of orderStatus
        # execDetails callback event is trigerred ONLY if the order placed is Executed
        client.execDetails_available.clear()  # internal flag is set to False
        if hasattr(client, "orderStatus_queue"
                   ):  # Clear the existing messages in the Q , if any
            with client.orderStatus_queue.mutex:
                client.orderStatus_queue.queue.clear()
        # Place the order
        client.placeOrder(client.orderId, contract, order)
        try:
            client.execDetails_available.wait(timeout=5)
        except:
            print(
                '    *** An Exception Occured in client.execDetails_available.wait(timeout=5) in close_open_position ***    '
            )
        else:  # if try condition is successful with no execption, this 'else' follows
            if client.order_executed == True:
                print("    *** \nOrder is Successfully Executed ***\n")
            else:
                print('    *** \nOrder NOT Executed ***\n')
            # Handle the q from orderStatus callback
            if hasattr(client, "orderStatus_queue"):
                while not client.orderStatus_queue.empty(
                ):  # If the queue is not empty
                    try:
                        order_status = client.orderStatus_queue.get(False)
                        print(
                            'Status of Order: {}, Filled Positions: {}, Remaining Positions: {}, OrderId: {}, permId: {}'
                            .format(order_status['status'],
                                    order_status['filled'],
                                    order_status['remaining'],
                                    order_status['orderId'],
                                    order_status['permId']))
                        if client.orderId == order_status[
                                'orderId']:  # for the latest orderId
                            if (order_status['status'] == 'Submitted') or (
                                    order_status['status'] == 'Filled'
                            ):  # if for even 1 message, the status is filled or submitted
                                client.order_submitted = True
                    except queue.Empty:
                        continue
                    client.orderStatus_queue.task_done(
                    )  # task_done() is used to inform task completion
                del client.orderStatus_queue  # Delete the queue
    else:
        print('Order ID not received. Terminating Application')
        client.disconnect()
        sys.exit()

    if (client.order_executed == True) or (client.order_submitted == True):
        position_closed = True  # set flag to True
    else:
        position_closed = False

    client.order_submitted = False  # reset the flag to False for future use
    client.order_executed = False  # reset the flag to False for future use
    return position_closed
예제 #5
0
def place_order_with_stop(client, action, quantity, stopLoss):
    ''' Place the Order with IB '''
    # Define the futures Contract prior to placing order
    contract = Contract()
    contract.localSymbol = client.local_symbol
    contract.secType = 'FUT'
    contract.exchange = 'NSE'
    contract.currency = 'INR'
    contract.primaryExchange = "NSE"

    # Request from TWS, the next valid ID for the order.
    client.nextValidId_available.clear()  # internal flag is set to False
    client.reqIds(-1)  # The parameter is always ignored.
    client.nextValidId_available.wait(
    )  # block thread until internal flag is set to True

    # Place the order
    if client.orderId:
        # for Market Orders use execDetails callback instead of orderStatus
        # execDetails callback event is trigerred ONLY if the order placed is Executed
        client.execDetails_available.clear()  # internal flag is set to False
        if hasattr(client, "orderStatus_queue"
                   ):  # Clear the existing messages in the Q , if any
            with client.orderStatus_queue.mutex:
                client.orderStatus_queue.queue.clear()

        bracket = NiftyORB.OrderWithStop(client.orderId, action, quantity,
                                         stopLoss)
        for o in bracket:
            client.orders_list.append(o.orderId)
            client.placeOrder(o.orderId, contract, o)

        try:
            client.execDetails_available.wait(timeout=5)
        except:
            print(
                '    *** An Exception Occured in client.execDetails_available.wait(timeout=5) in place_order_with_stop ***    '
            )
        else:  # if try condition is successful with no execption, this 'else' follows
            if client.order_executed == True:
                print("    *** \nOrder is Successfully Executed ***\n")
            else:
                print('    *** \nOrder NOT Executed ***\n')

            # Handle the q from orderStatus callback
            # https://stackoverflow.com/questions/6517953/clear-all-items-from-the-queue
            if hasattr(client, "orderStatus_queue"):
                while not client.orderStatus_queue.empty(
                ):  # If the queue is not empty
                    try:
                        order_status = client.orderStatus_queue.get(False)
                        print(
                            'Status of Order: {}, Filled Positions: {}, Remaining Positions: {}, OrderId: {}, permId: {}'
                            .format(order_status['status'],
                                    order_status['filled'],
                                    order_status['remaining'],
                                    order_status['orderId'],
                                    order_status['permId']))
                        if client.orderId == order_status[
                                'orderId']:  # for the latest orderId
                            if (order_status['status'] == 'Submitted') or (
                                    order_status['status'] == 'Filled'
                            ):  # if for even 1 message, the status is filled or submitted
                                client.order_submitted = True
                    except queue.Empty:
                        continue
                    client.orderStatus_queue.task_done(
                    )  # task_done() is used to inform task completion
                # del client.orderStatus_queue # Delete the queue
    else:
        print('Order ID not received. Terminating Application')
        client.disconnect()
        sys.exit()

    if (client.order_executed == True) or (client.order_submitted == True):
        order_placed = True  # set flag to True
    else:
        order_placed = False

    client.order_submitted = False  # reset the flag to False for future use
    client.order_executed = False  # reset the flag to False for future use
    return order_placed