Example #1
0
def generate_generic_manual_fill(data):
    stack = resolve_stack(data, exclude_instrument_stack=True)
    view_generic_stack(stack)
    order_id = get_and_convert("Enter order ID",
                               default_str="Cancel",
                               default_value="")
    if order_id == "":
        return None
    order = stack.get_order_with_id_from_stack(order_id)
    print("Order now %s" % str(order))
    # FIX ME HANDLE SPREAD ORDERS
    fill_qty = get_and_convert(
        "Quantity to fill (must be less than or equal to %s)" %
        str(order.trade),
        type_expected=int,
        allow_default=True,
        default_value=order.trade)
    if type(fill_qty) is int:
        fill_qty = [fill_qty]
    filled_price = get_and_convert("Filled price",
                                   type_expected=float,
                                   allow_default=False)
    fill_datetime = get_datetime_input("Fill datetime", allow_default=True)

    stack.manual_fill_for_order_id(order_id,
                                   fill_qty,
                                   filled_price=filled_price,
                                   fill_datetime=fill_datetime)
    order = stack.get_order_with_id_from_stack(order_id)

    print("Order now %s" % str(order))
    print(
        "If stack process not running, your next job will be to pass fills upwards"
    )
def get_values_from_user_to_modify():
    broker_account_value = get_and_convert(
        "Broker account value",
        type_expected=float,
        default_value=arg_not_supplied,
        default_str="Unchanged",
    )
    total_capital = get_and_convert(
        "Total capital at risk",
        type_expected=float,
        default_value=arg_not_supplied,
        default_str="Unchanged",
    )
    maximum_capital = get_and_convert(
        "Max capital, only used for half compounding",
        type_expected=float,
        default_value=arg_not_supplied,
        default_str="Unchanged",
    )
    acc_pandl = get_and_convert(
        "Accumulated profit",
        type_expected=float,
        default_value=arg_not_supplied,
        default_str="Unchanged",
    )

    return broker_account_value, total_capital, maximum_capital, acc_pandl
Example #3
0
def create_instrument_balance_trade(data):
    data_broker = dataBroker(data)
    default_account = data_broker.get_broker_account()

    print(
        "Use to fix breaks between instrument strategy and contract level positions"
    )
    strategy_name = get_valid_strategy_name_from_user(data=data)
    instrument_code = get_valid_instrument_code_from_user(data)
    fill_qty = get_and_convert("Quantity ",
                               type_expected=int,
                               allow_default=False)
    filled_price = get_and_convert("Filled price",
                                   type_expected=float,
                                   allow_default=False)
    fill_datetime = get_datetime_input("Fill datetime", allow_default=True)

    instrument_order = instrumentOrder(
        strategy_name,
        instrument_code,
        fill_qty,
        fill=fill_qty,
        order_type="balance_trade",
        filled_price=filled_price,
        fill_datetime=fill_datetime,
    )

    print(instrument_order)
    ans = input("Are you sure? (Y/other)")
    if ans != "Y":
        return None

    stack_handler = stackHandlerCreateBalanceTrades(data)

    stack_handler.create_balance_instrument_trade(instrument_order)
Example #4
0
def enter_manual_instrument_order(data):
    strategy_name = get_valid_strategy_name_from_user(data=data)
    instrument_code = get_valid_instrument_code_from_user(data)
    qty = get_and_convert("Quantity (-ve for sell, +ve for buy?)",
                          type_expected=int,
                          allow_default=False)
    order_type = input("Order type (one of %s)?" % str(possible_order_types))
    limit_price = get_and_convert(
        "Limit price? (if you put None you can still add one to the contract order)",
        type_expected=float,
        default_value=None,
        default_str="None",
    )
    if limit_price is None:
        limit_contract = None
    else:
        print("Enter contractid that limit price is referenced to")
        _, contract_date = get_valid_instrument_code_and_contractid_from_user(
            data, instrument_code=instrument_code)
        limit_contract = contract_date

    instrument_order = instrumentOrder(
        strategy_name,
        instrument_code,
        qty,
        order_type=order_type,
        limit_price=limit_price,
        limit_contract=limit_contract,
        manual_trade=True,
        roll_order=False,
    )

    return instrument_order
def get_initial_capital_values_from_user(data: dataBlob):
    broker_account_value = get_and_convert(
        "Broker account value",
        type_expected=float,
        default_str="get from IB",
        default_value=arg_not_supplied,
    )
    if broker_account_value is arg_not_supplied:
        broker_account_value = get_broker_account_value(data)
        print("Got broker account value of %f from IB" % broker_account_value)

    total_capital = get_and_convert(
        "Total capital at risk",
        type_expected=float,
        default_value=broker_account_value)

    maximum_capital = get_and_convert(
        "Max capital, only used for half compounding",
        type_expected=float,
        default_value=total_capital,
    )

    acc_pandl = get_and_convert(
        "Accumulated profit", type_expected=float, default_value=0.0
    )

    return broker_account_value, total_capital, maximum_capital, acc_pandl
Example #6
0
def create_balance_trade(data):
    data_broker = dataBroker(data)
    default_account = data_broker.get_broker_account()

    print("Most likely use case here is that IB has closed one of your positions as close to the expiry")
    print("Or an edge case in which an order was submitted and then filled whilst you were not monitoring fills")
    print("Trades have to be attributed to a strategy (even roll trades)")
    strategy_name = get_valid_strategy_name_from_user()
    instrument_code, contract_date = get_valid_instrument_code_and_contractid_from_user(data)
    fill_qty = get_and_convert("Quantity ", type_expected=int, allow_default=False)
    filled_price = get_and_convert("Filled price", type_expected=float, allow_default=False)
    fill_datetime  =get_datetime_input("Fill datetime", allow_default=True)
    commission = get_and_convert("Commission", type_expected=float, allow_default=True, default_value=0.0)
    broker_account = get_and_convert("Account ID", type_expected=str, allow_default=True, default_value=default_account)

    broker_order = brokerOrder(strategy_name, instrument_code, contract_date, [fill_qty],
                               fill = [fill_qty],
                               algo_used="balance_trade",
                               order_type="balance_trade",
                               filled_price = filled_price,
                               fill_datetime = fill_datetime,
                               broker_account = broker_account,
                               commission = commission, manual_fill=True,
                               active = False)

    print(broker_order)
    ans = input("Are you sure? (Y/other)")
    if ans !="Y":
        return None

    stack_handler = stackHandlerCreateBalanceTrades(data)

    stack_handler.create_balance_trade(broker_order)
Example #7
0
def get_risk_multiplier() -> float:
    print("Enter parameters to estimate typical position sizes")
    notional_risk_target = get_and_convert("Notional risk target (% per year)", type_expected=float, default_value=.25)
    approx_IDM = get_and_convert("Approximate IDM", type_expected=float, default_value=2.5)
    notional_instrument_weight = get_and_convert("Notional instrument weight (go large for safety!)",
                                                 type_expected=float, default_value=.1)

    return notional_risk_target * approx_IDM * notional_instrument_weight
Example #8
0
def change_limit_for_instrument(data):
    trade_limits = dataTradeLimits(data)
    instrument_code = get_valid_instrument_code_from_user(data)
    period_days = get_and_convert("Period of days?", type_expected=int, allow_default=True, default_value = 1)
    new_limit = get_and_convert("Limit (in contracts?)", type_expected=int, allow_default=False)
    ans = input("Update will change number of trades allowed in periods, but won't reset 'clock'. Are you sure? (y/other)")
    if ans =="y":
        trade_limits.update_instrument_limit_with_new_limit(instrument_code, period_days, new_limit)
Example #9
0
def enter_manual_contract_order(data, instrument_order):
    strategy_name = instrument_order.strategy_name
    instrument_code = instrument_order.instrument_code
    qty = instrument_order.trade

    leg_count = get_and_convert("How many legs?",
                                type_expected=int,
                                default_value=1)
    contract_id_list = []
    for leg_idx in range(leg_count):
        print("Choose contract for leg %d" % leg_idx)
        _, contract_date = get_valid_instrument_code_and_contractid_from_user(
            data, instrument_code=instrument_code)
        contract_id_list.append(contract_date)

    trade_qty_list = []
    for trade_idx in range(leg_count):
        trade_qty = get_and_convert(
            "Enter quantity for leg %d" % trade_idx,
            type_expected=int,
            allow_default=False,
        )
        trade_qty_list.append(trade_qty)

    if sum(trade_qty_list) != sum(qty):
        print(
            "Sum of instrument quantity %s is different from sum of contract quantity %s"
            % (str(qty), str(trade_qty_list)))
        print("It's unlikely you meant to do this...")

    NO_ALGO = "None: allow system to allocate"
    algo_to_use = print_menu_of_values_and_get_response(list_of_algos,
                                                        default_str=NO_ALGO)
    if algo_to_use == NO_ALGO:
        algo_to_use = ""

    limit_price = get_and_convert(
        "Limit price? (will override instrument order limit price, will be ignored by some algo types",
        type_expected=float,
        default_str="None",
        default_value=None,
    )

    order_type = map_instrument_order_type_to_contract_order_type(
        instrument_order.order_type)
    contract_order = contractOrder(
        strategy_name,
        instrument_code,
        contract_id_list,
        trade_qty_list,
        algo_to_use=algo_to_use,
        order_type=order_type,
        reference_price=None,
        limit_price=limit_price,
        manual_trade=True,
    )

    return contract_order
Example #10
0
def auto_populate_limits(data: dataBlob):
    instrument_list = get_list_of_instruments(data)
    risk_multiplier = get_risk_multiplier()
    trade_multiplier = get_and_convert("Higgest proportion of standard position expected to trade daily?",
                                       type_expected=float, default_value=0.33)
    day_count = get_and_convert("What period in days to set limit for?", type_expected=int, default_value=1)
    _ = [set_trade_limit_for_instrument(data, instrument_code, risk_multiplier, trade_multiplier, day_count)
                        for instrument_code in instrument_list]
    return None
Example #11
0
def generate_generic_manual_fill(data):
    stack = resolve_stack(data, exclude_instrument_stack=True)
    view_generic_stack(stack)
    order_id = get_and_convert("Enter order ID",
                               default_str="Cancel",
                               default_value="")
    if order_id == "":
        return None
    order = stack.get_order_with_id_from_stack(order_id)
    if order is missing_order:
        print("Order doesn't exist on stack")
        return None
    if len(order.trade) > 1:
        print(
            "Can't manually fill spread orders; delete and replace with legs")
        return None
    if not order.no_children():
        print(
            "Don't manually fill order with children: can cause problems! Manually fill the child instead"
        )
        return None
    print("Order now %s" % str(order))
    fill_qty = get_and_convert(
        "Quantity to fill (must be less than or equal to %s)" %
        str(order.trade),
        type_expected=int,
        allow_default=True,
        default_value=order.trade,
    )
    if isinstance(fill_qty, int):
        fill_qty = [fill_qty]
    filled_price = get_and_convert("Filled price",
                                   type_expected=float,
                                   allow_default=False)
    fill_datetime = get_datetime_input("Fill datetime", allow_default=True)

    order = stack.get_order_with_id_from_stack(order_id)

    order.fill_order(fill_qty=fill_qty,
                     filled_price=filled_price,
                     fill_datetime=fill_datetime)

    stack.mark_as_manual_fill_for_order_id(order_id)

    stack_handler = stackHandler()
    if type(order) is brokerOrder:
        ## pass up and change positions
        stack_handler.apply_broker_order_fills_to_database(order)
    else:
        stack_handler.apply_contract_order_fill_to_database(order)

    order = stack.get_order_with_id_from_stack(order_id)
    print("Order now %s" % str(order))
    print(
        "If stack process not running, your next job will be to pass fills upwards"
    )
Example #12
0
def create_fx_trade(data):
    data_broker = dataBroker(data)
    fx_balance = data_broker.broker_fx_balances()
    print("Current FX balances")
    print(fx_balance)
    print(
        "Remember to check how much you need for margin as you will be charged interest if insufficient"
    )
    default_account = data_broker.get_broker_account()
    broker_account = get_and_convert(
        "Account ID",
        type_expected=str,
        allow_default=True,
        default_value=default_account,
    )

    invalid = True
    while invalid:
        print("First currency")
        ccy1 = get_and_convert(
            "First currency",
            allow_default=True,
            default_value=None,
            default_str="Cancel",
            type_expected=str,
        )
        if ccy1 is None:
            return None
        ccy2 = get_and_convert("Second currency",
                               default_value="USD",
                               type_expected=str)
        if ccy1 == ccy2:
            print("%s==%s. Not allowed!" % (ccy1, ccy2))
            continue
        qty = get_and_convert(
            "Amount of trade in %s%s" % (ccy1, ccy2),
            type_expected=int,
            allow_default=False,
        )
        if qty < 0:
            print("Selling %d of %s, buying %s" % (qty, ccy1, ccy2))
        elif qty > 0:
            print("Buying %d of %s, buying %s" % (qty, ccy1, ccy2))

        ans = input("Are you sure that's right? Y-yes / other")
        if ans != "Y":
            continue
        else:
            break

    result = data_broker.broker_fx_market_order(qty,
                                                ccy1,
                                                account=broker_account,
                                                ccy2=ccy2)
    print("%s" % result)
def modify_instrument_order(data):
    stack_handler = stackHandler(data)

    order_id = get_and_convert("Enter order ID", type_expected=int, default_str="Cancel", default_value=0)
    if order_id ==0:
        return None
    order = stack_handler.instrument_stack.get_order_with_id_from_stack(order_id)
    print("Existing order %s" % str(order))
    new_qty = get_and_convert("New quantity (zero to cancel)", type_expected=int, default_value = order.trade)
    stack_handler.instrument_stack.modify_order_on_stack(order_id, new_qty)
    print("You will probably want to push modifications down to contract orders next, if not running on auto")
def enter_manual_contract_order(data, instrument_order):
    strategy_name = instrument_order.strategy_name
    instrument_code = instrument_order.instrument_code
    qty = instrument_order.trade

    leg_count = get_and_convert("How many legs?",
                                type_expected=int,
                                default_value=1)
    contract_id_list = []
    for leg_idx in range(leg_count):
        print("Choose contract for leg %d" % leg_idx)
        _, contract_date = get_valid_instrument_code_and_contractid_from_user(
            data, instrument_code=instrument_code)
        contract_id_list.append(contract_date)

    trade_qty_list = []
    for trade_idx in range(leg_count):
        trade_qty = get_and_convert("Enter quantity for leg %d" % trade_idx,
                                    type_expected=int,
                                    allow_default=False)
        trade_qty_list.append(trade_qty)

    if sum(trade_qty_list) != sum(qty):
        print(
            "Sum of instrument quantity %s is different from sum of contract quantity %s"
            % (str(qty), str(trade_qty_list)))
        print("It's unlikely you meant to do this...")

    algo_to_use = get_and_convert(
        "Algo to use (Full function eg sysexecution.algos.algo_market.algo_market)",
        type_expected=str,
        default_str="None: Algo will be allocated automatically",
        default_value="")
    limit_price = get_and_convert(
        "Limit price? (will override instrument order limit price, will be ignored by some algo types",
        type_expected=float,
        default_str="None",
        default_value=None)

    contract_order = contractOrder(
        strategy_name,
        instrument_code,
        contract_id_list,
        trade_qty_list,
        algo_to_use=algo_to_use,
        reference_price=None,
        limit_price=limit_price,
        manual_trade=True,
    )

    return contract_order
Example #15
0
def reset_limit_for_instrument(data):
    trade_limits = dataTradeLimits(data)
    instrument_code = get_valid_instrument_code_from_user(data)
    period_days = get_and_convert("Period of days?", type_expected=int, allow_default=True, default_value = 1)
    ans = input("Reset means trade 'clock' will restart. Are you sure? (y/other)")
    if ans =="y":
        trade_limits.reset_instrument_limit(instrument_code, period_days)
def view_individual_order(data):
    list_of_order_types = [
        "Instrument / Strategy",
        "Instrument / Contract",
        "Broker level",
    ]
    print("Which order queue?")
    order_type = print_menu_of_values_and_get_response(list_of_order_types)
    order_id = get_and_convert("Order number?",
                               type_expected=int,
                               default_value=None,
                               default_str="CANCEL")
    if order_id is None:
        return None

    data_orders = dataOrders(data)
    if order_type == list_of_order_types[0]:
        order = data_orders.get_historic_instrument_order_from_order_id(
            order_id)
    elif order_type == list_of_order_types[1]:
        order = data_orders.get_historic_contract_order_from_order_id(order_id)
    elif order_type == list_of_order_types[2]:
        order = data_orders.get_historic_broker_order_from_order_id(order_id)

    print(order)

    return None
Example #17
0
def order_locking(data):
    stack = resolve_stack(data)
    if stack is None:
        return None
    view_generic_stack(stack)
    order_id = get_and_convert("Order ID ",
                               type_expected=int,
                               allow_default=False)
    order = stack.get_order_with_id_from_stack(order_id)
    print(order)

    if order.is_order_locked():
        ans = input("Unlock order? <y/other>")
        if ans == "y":
            stack._unlock_order_on_stack(order_id)
        else:
            return None

    else:
        ans = input("Lock order? <y/other>")
        if ans == "y":
            stack._lock_order_on_stack(order_id)
        else:
            return None

    return None
Example #18
0
def get_fills_from_broker(data):
    stack_handler = stackHandler(data)

    print(
        "This will get any fills from the broker, and write them to the broker stack"
    )
    print("Broker orders: (in database)")
    view_broker_stack(data)
    broker_order_id = get_and_convert(
        "Which broker order ID?",
        default_value="ALL",
        default_str="for all",
        type_expected=int,
    )
    ans = input("Are you sure? (Y/other)")
    if ans != "Y":
        return None
    if broker_order_id == "ALL":
        stack_handler.pass_fills_from_broker_to_broker_stack()
    else:
        stack_handler.apply_broker_fill_to_broker_stack(broker_order_id)

    print(
        "If stack process not running, your next job will be to pass fills from broker to contract stack"
    )
Example #19
0
def generate_ib_orders(data):
    stack_handler = stackHandler(data)

    print("This will create broker orders and submit to IB")
    print("Contract orders:")
    view_contract_stack(data)
    contract_order_id = get_and_convert(
        "Which contract order ID?",
        default_value="ALL",
        default_str="for all",
        type_expected=int,
    )
    ans = input("Are you sure? (Y/other)")
    if ans != "Y":
        return None
    ans = input("Check if market open? <return for YES / other>")
    if ans != "":
        check_if_open = False
    else:
        check_if_open = True

    if contract_order_id == "ALL":
        stack_handler.create_broker_orders_from_contract_orders(
            check_if_open=check_if_open)
    else:
        stack_handler.create_broker_order_for_contract_order(
            contract_order_id, check_if_open=check_if_open)

    print(
        "If stack process not running, your next job will be to get the fills from IB"
    )
Example #20
0
def spawn_contracts_from_instrument_orders(data):
    stack_handler = stackHandler(data)

    print(
        "This will create contract orders for any instrument orders that don't have them"
    )
    print("Instrument orders:")
    view_instrument_stack(data)
    order_id = get_and_convert(
        "Which instrument order ID",
        default_value="ALL",
        default_str="All",
        type_expected=int,
    )
    check_ans = input("Are you sure? (Y/other)")
    if check_ans != "Y":
        return None
    if order_id == "ALL":
        stack_handler.spawn_children_from_new_instrument_orders()
    else:
        stack_handler.spawn_children_from_instrument_order_id(order_id)

    print(
        "If you are trading manually, you should now view the contract order stack and trade."
    )
    print("Then create manual fills for contract orders")
def retrieve_emails(data):
    subject = get_and_convert("Subject of emails (copy from emails)?",
                              type_expected=str,
                              allow_default=True,
                              default_value=None)
    messages = retrieve_and_delete_stored_messages(data, subject=subject)
    for msg in messages:
        print(msg)
def order_view(data):
    stack = resolve_stack(data)
    if stack is None:
        return None
    order_id = get_and_convert("Order ID?", type_expected=int, allow_default=False)
    order = stack.get_order_with_id_from_stack(order_id)
    print("%s" % order)

    return None
def view_logs(data):
    diag_logs = diagLogs(data)
    lookback_days = get_and_convert("How many days?",
                                    type_expected=int,
                                    default_value=7)
    attribute_dict = build_attribute_dict(diag_logs, lookback_days)
    log_item_list = diag_logs.get_log_items(attribute_dict=attribute_dict,
                                            lookback_days=lookback_days)
    print(log_item_list)
Example #24
0
def email_or_print(report_config):
    ans = get_and_convert("1: Email or 2: print?", type_expected=int, allow_default=True, default_str="Print",
                    default_value=2)
    if ans==1:
        report_config = report_config.new_config_with_modified_output("email")
    else:
        report_config = report_config.new_config_with_modified_output("console")

    return report_config
Example #25
0
def change_position_limit_for_instrument(data):
    data_position_limits = dataPositionLimits(data)
    instrument_code = get_valid_instrument_code_from_user(data, allow_all=False)
    new_position_limit = get_and_convert("New position limit?", type_expected=int, allow_default=True,
                                         default_str="No limit", default_value=-1)
    if new_position_limit==-1:
        data_position_limits.delete_position_limit_for_instrument(instrument_code)
    else:
        new_position_limit = abs(new_position_limit)
        data_position_limits.set_abs_position_limit_for_instrument(instrument_code, new_position_limit)
def complete_modification_for_contract(data):
    stack_handler = stackHandler(data)

    order_id = get_and_convert("Which contract order ID", default_value=0, default_str="CANCEL", type_expected=int)
    if order_id ==0:
        return None
    else:
        stack_handler.contract_stack.completed_modifying_order_on_stack(order_id)

    print("If you are trading manually, you will now want to pass the modification complete from contract to instruments")
Example #27
0
def view_errors(data):
    diag_logs = diagLogs(data)
    msg_levels = diag_logs.get_possible_log_level_mapping()
    print("This will get all log messages with a given level of criticality")
    print("Use view logs to filter by log attributes")
    lookback_days = get_and_convert("How many days?", type_expected=int, default_value=7)
    print("Which level of error/message?")
    log_level = print_menu_and_get_response(msg_levels)
    log_item_list = diag_logs.get_log_items_with_level(log_level, attribute_dict=dict(), lookback_days=lookback_days)
    print_log_items(log_item_list)
Example #28
0
def generate_manual_contract_fill(stack_handler):
    print(
        "Manually fill a contract order. Use only if no broker order has been generated."
    )
    order_id = get_and_convert("Enter contract order ID",
                               default_str="Cancel",
                               default_value="")
    if order_id == "":
        return None
    try:
        order = stack_handler.contract_stack.get_order_with_id_from_stack(
            order_id)
        print("Order now %s" % str(order))
        # FIX ME HANDLE SPREAD ORDERS
        fill_qty = get_and_convert(
            "Quantity to fill (must be less than or equal to %s)" %
            str(order.trade),
            type_expected=int,
            allow_default=True,
            default_value=order.trade)
        if type(fill_qty) is int:
            fill_qty = [fill_qty]
        filled_price = get_and_convert("Filled price",
                                       type_expected=float,
                                       allow_default=False)
        fill_datetime = get_datetime_input("Fill datetime", allow_default=True)

        stack_handler.contract_stack.manual_fill_for_contract_id(
            order_id,
            fill_qty,
            filled_price=filled_price,
            fill_datetime=fill_datetime)
        order = stack_handler.contract_stack.get_order_with_id_from_stack(
            order_id)

        print("Order now %s" % str(order))
        print(
            "If stack process not running, your next job will be to pass fills upwards"
        )

    except Exception as e:
        print("%s went wrong!" % e)
Example #29
0
def get_valid_strategy_name_from_user():
    all_strategies = get_list_of_strategies()
    invalid_input = True
    while invalid_input:
        print("Strategies: %s" % all_strategies)
        default_strategy = all_strategies[0]
        strategy_name = get_and_convert("Strategy?", type_expected=str, default_value=default_strategy)
        if strategy_name in all_strategies:
            return strategy_name

        print("%s is not in list %s" % (strategy_name, all_strategies))
Example #30
0
def clear_algo_on_order(data):
    stack_handler = stackHandler(data)
    stack = stack_handler.contract_stack
    view_generic_stack(stack)
    order_id = get_and_convert("Order ID ",
                               type_expected=int,
                               allow_default=False)
    order = stack.get_order_with_id_from_stack(order_id)
    print("Controlled by %s; releasing now" %
          str(order.reference_of_controlling_algo))
    stack.release_order_from_algo_control(order_id)
    print("Released")