Example #1
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders

        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Subscribe to open positions of all accounts")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        for account in accounts:
            account.AutoSubscribeInstruments = True
            account.PositionSubcriptionLevel = constants.pslSnapshotAndUpdates
            Trace("GW Account id: {} name: {}".format(account.GWAccountID,
                                                      account.GWAccountName))

        Trace("Select the first account")
        interestingAccount = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace(
            "Query orders in NotFinal state for account (gw id: {} name: {})".
            format(interestingAccount.GWAccountID,
                   interestingAccount.GWAccountName))
        ordersRequest = self.celEnvironment.cqgCEL.CreateOrdersRequest()
        ordersRequest.Account = interestingAccount
        ordersRequest.StatusFilter = constants.osfNotFinal
        ordersRequest.Date = datetime.now(timezone.utc)
        ordersRequest.Side = constants.osdUndefined

        self.orderQuery = self.celEnvironment.cqgCEL.RequestOrders(
            ordersRequest)

        Trace("Waiting for orders query completeness...")
        AssertMessage(self.eventOrdersQueryIsReady.wait(TIMEOUT),
                      "Orders query timeout!")

        Trace("press Enter to stop..")
        input()

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
Example #2
0
    def Start(self):
        Trace("Connecting to GW ({})".format(LOGIN))
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT), "GW connection timeout!")

        input("press Enter to Logoff..")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT), "GW disconnection timeout!")

        Trace("Done!")
Example #3
0
 def Close(self):
     Trace("Logoff from GW")
     self.eventGatewayIsDown.clear()
     self.celEnvironment.cqgCEL.GWLogoff()
     AssertMessage(self.eventGatewayIsDown.wait(GATEWAYDOWN_TIMEOUT),
                   "GW disconnection timeout!")
     Trace("Done!")
Example #4
0
    def Open(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(self.username, self.password)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(GATEWAYUP_TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(ACCOUNT_LOGIN_TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))
        return self.account
Example #5
0
    def Start(self):
        Trace("{} instrument requesting...".format(self.symbol))
        self.celEnvironment.cqgCEL.NewInstrument(self.symbol)
        Trace("{} instrument waiting...".format(self.symbol))
        AssertMessage(self.eventInstrumentIsReady.wait(INSTRUMENT_SETUP_TIMEOUT), f"{self.symbol} Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        if self.tradeTrigger == 1:
            bestTrade = dispatchedInstrument.Ask
        elif self.tradeTrigger == -1:
            bestTrade = dispatchedInstrument.Bid
        AssertMessage(bestTrade.IsValid, f"Error! Can't set {self.symbol}'s order price due to invalid BBA")
        Trace("{}'s best price is {}".format(self.symbol, bestTrade.Price))

        if self.tradeTrigger != 0 and self.SignalOperationCalc(bestTrade.Price, self.signalDirection):
            return True, bestTrade.Price

        return False, bestTrade.Price
Example #6
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        # Select an account that has enablement for UDS
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("Define strategy...")
        self.uds = self.celEnvironment.cqgCEL.DefineStrategy(STRATEGY)

        Trace("UDS waiting...")
        AssertMessage(self.eventUDSIsReady.wait(TIMEOUT),
                      "UDS resolution timeout!")

        dispatchedUDS = win32com.client.Dispatch(self.uds)
        dispatchedOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateStrategyOrder(
                constants.otLimit, dispatchedUDS, self.account, None, 1,
                constants.osdUndefined, 3.15))
        dispatchedOrder.Place()

        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslNone
        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountsOnly
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))
        for account in accounts:
            Trace("GW Account id: {} name: {}".format(account.GWAccountID,
                                                      account.GWAccountName))

        statementDate = datetime.now(timezone.utc) - timedelta(days=1)

        Trace(
            "Request positions statement for GW account ID = {} for date: {}".
            format(self.account.GWAccountID, statementDate))

        self.celEnvironment.cqgCEL.QueryPositionsStatement(
            self.account.GWAccountID, statementDate)

        Trace("Waiting for positions statement coming...")
        AssertMessage(self.eventPositionsStatementReady.wait(TIMEOUT),
                      "Positions statement coming timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting...".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        bestBid = dispatchedInstrument.Bid
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Calculating a price that below the market by 10 tick sizes")
        buyOrderPrice = bestBid.Price - 10 * dispatchedInstrument.TickSize
        Trace("It is {}".format(buyOrderPrice))
        Trace("Create Buy limit order")
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))

        properties = win32com.client.Dispatch(buyOrder.Properties)
        speculationType = properties(constants.opSpeculationType)
        speculationType.Value = constants.sptHedge
        Trace("An order speculation type is set to {}".format(
            speculationType.Value))

        Trace("Place order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
Example #9
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account...")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting...".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        bestBid = dispatchedInstrument.Bid
        offsetFromBestBid = 10
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Create Buy limit order")
        buyOrderPrice = bestBid.Price - offsetFromBestBid * dispatchedInstrument.TickSize
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))

        buyOrder.MiFIDAlgorithmID = "My-Own-MiFID-Algo-ID"
        Trace("Set MiFID algorithm ID to {}".format(buyOrder.MiFIDAlgorithmID))

        Trace("Place order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
Example #10
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(self.username, self.password)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(GATEWAYUP_TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(ACCOUNT_LOGIN_TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting...".format(self.symbol))
        self.celEnvironment.cqgCEL.NewInstrument(self.symbol)
        Trace("{} instrument waiting...".format(self.symbol))
        AssertMessage(
            self.eventInstrumentIsReady.wait(INSTRUMENT_SETUP_TIMEOUT),
            f"{self.symbol} Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        if self.tradeTrigger == 1:
            bestBid = dispatchedInstrument.Ask
            AssertMessage(
                bestBid.IsValid,
                f"Error! Can't set {self.symbol}'s order price due to invalid BBA"
            )
            Trace("Best ask value is {}".format(bestBid.Price))
            orderPrice = bestBid.Price + self.tick
            Trace("Order price to submit is {}".format(orderPrice))
            orderSide = constants.osdBuy
        elif self.tradeTrigger == -1:
            bestAsk = dispatchedInstrument.Bid
            AssertMessage(
                bestAsk.IsValid,
                f"Error! Can't set {self.symbol}'s order price due to invalid BBA"
            )
            Trace("Best bid value is {}".format(bestAsk.Price))
            orderPrice = bestAsk.Price + self.tick
            Trace("Order price to submit is {}".format(orderPrice))
            orderSide = constants.osdSell

        Trace("Create limit order")
        minutes_passed = 0
        while minutes_passed < self.executionTime:
            if minutes_passed >= 1:
                Trace("Cancel unfilled {} orders.(Format)".format(
                    self.leftOrderCount))
                self.celEnvironment.cqgCEL.CancelAllOrders(
                    self.account, None, False, False, orderSide)

                Trace(
                    "Waiting for {} orders to be cancelled...(Format)".format(
                        self.leftOrderCount))
                AssertMessage(
                    self.eventOrderCancelled.wait(ORDER_CANCEL_TIMEOUT),
                    f"{self.symbol}'s Order cancellation timeout!")

            order = win32com.client.Dispatch(
                self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                       self.instrument,
                                                       self.account,
                                                       self.leftOrderCount,
                                                       orderSide, orderPrice))
            Trace("Place order")
            try:
                order.Place()
            except Exception as e:
                AssertMessage(False, f"{self.symbol}: {str(e)}")

            try:
                Trace("Waiting for {} orders placing...".format(
                    self.leftOrderCount))
                AssertMessage(self.eventOrderPlaced.wait(ORDER_PLACE_TIMEOUT),
                              f"{self.symbol}'s Order placing timeout!")
            except Exception as e:
                Trace("Exception: {}".format(str(e)))
                Trace("Cancel failed {} placing orders.(Format)".format(
                    self.leftOrderCount))
                self.celEnvironment.cqgCEL.CancelAllOrders(
                    self.account, None, False, False, orderSide)

            time.sleep(60)
            minutes_passed = minutes_passed + 1
            if self.leftOrderCount == 0:
                break

        if self.leftOrderCount > 0:
            Trace("Cancel unfilled {} orders.(Format)".format(
                self.leftOrderCount))
            self.celEnvironment.cqgCEL.CancelAllOrders(self.account, None,
                                                       False, False, orderSide)

            Trace("Waiting for {} orders to be cancelled...(Format)".format(
                self.leftOrderCount))
            AssertMessage(self.eventOrderCancelled.wait(ORDER_CANCEL_TIMEOUT),
                          f"{self.symbol}'s Order cancellation timeout!")

        return self.leftOrderCount
Example #11
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("Define strategy...")
        definedStrategy = self.celEnvironment.cqgCEL.DefineStrategy(STRATEGY)

        Trace("Waiting for strategy resolution...")
        AssertMessage(self.eventStrategyIsReady.wait(TIMEOUT),
                      "Strategy resolution timeout!")

        self.dispatchedStrategy = win32com.client.Dispatch(definedStrategy)

        Trace(
            "Subscribe to {} for a best ask value receiving. It will be used for an order placing..."
            .format(STRATEGY))
        self.celEnvironment.cqgCEL.NewInstrument(STRATEGY)
        Trace("{} subscription waiting...".format(STRATEGY))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        instrument = win32com.client.Dispatch(self.instrument)

        bestAsk = instrument.Ask
        AssertMessage(bestAsk.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Best ask value is {}".format(bestAsk.Price))
        Trace("Calculating a price that above the market by 10 tick sizes...")
        sellOrderPrice = bestAsk.Price + 10 * instrument.TickSize
        Trace("It is {}".format(sellOrderPrice))

        Trace("Starting a limit sell order creation procedure...")
        order = self.createOrder(-1, sellOrderPrice)

        Trace("Place the order...")
        order.Place()

        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done.")
Example #12
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT), "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT), "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting...".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT), "Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        bestBid = dispatchedInstrument.Bid
        AssertMessage(bestBid.IsValid, "Error! Can't set an order price due to invalid BBA")

        Trace("Best bid value is {}".format(bestBid.Price))
        Trace("Calculating a price that below the market by 10 tick sizes...")
        buyOrderPrice = bestBid.Price - 10 * dispatchedInstrument.TickSize
        Trace("It is {}".format(buyOrderPrice))

        Trace("Creating two buy limit orders...")
        buyOrders = []
        buyOrders.append(self.createOrder(1, buyOrderPrice))
        buyOrders.append(self.createOrder(1, buyOrderPrice - 2 * dispatchedInstrument.TickSize))

        Trace("Creating an order chain for initial compound order...")
        orderChain = win32com.client.Dispatch(self.celEnvironment.cqgCEL.CreateOrderChain())
        orderChain.AddOrder(buyOrders[0])
        orderChain.AddOrder(buyOrders[1])

        Trace("Place the compound order")
        self.celEnvironment.cqgCEL.PlaceCompoundOrder(orderChain)
        Trace("Waiting for compound order legs placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT), "Order placing timeout!")

        sellOrderPrice = bestBid.Price
        Trace(
            "Create a sell limit order for the compound order extending. The order price is {}".format(sellOrderPrice))
        sellOrder = self.createOrder(-1, sellOrderPrice)

        Trace("Create an order chain for the compound order extending")
        newOrderChain = self.celEnvironment.cqgCEL.CreateOrderChain()
        newOrderChain.AddOrder(sellOrder)

        Trace("Modifying the compound order...")
        self.celEnvironment.cqgCEL.ModifyCompoundOrder(self.compoundOrderID, self.compoundOrderGUID, newOrderChain)

        Trace("Waiting for the order filling...")
        AssertMessage(self.eventOrderFilled.wait(TIMEOUT), "Order filling timeout!")
        Trace("Waiting for two orders canceling...")
        AssertMessage(self.eventOrderCanceled.wait(TIMEOUT), "Order canceling timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT), "GW disconnection timeout!")

        Trace("Done!")
Example #13
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        dispatchedInstrument = win32com.client.Dispatch(self.instrument)

        bestBid = dispatchedInstrument.Bid
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Best bid value is {}".format(bestBid.Price))
        Trace("Calculating a price that above the market by 10 tick sizes...")
        buyOrderPrice = bestBid.Price - 10 * dispatchedInstrument.TickSize
        Trace("It is {}".format(buyOrderPrice))

        Trace("Create Buy limit order")
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))

        Trace("Set Good-Till-Date property of the order")
        buyOrder.DurationType = constants.odGoodTillDate
        properties = win32com.client.Dispatch(buyOrder.Properties)
        gtdTime = properties(constants.opGTDTime)

        dateGTD = datetime.now(timezone.utc) + timedelta(days=7)
        gtdTime.Value = dateGTD
        Trace("Good-Till-Date property is set to {}".format(dateGTD))

        Trace("Place order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("Account name: {}".format(self.account.GWAccountName))

        Trace("{} instrument requesting".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        instrument = win32com.client.Dispatch(self.instrument)

        bestBid = instrument.Bid
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Best bid value is {}".format(bestBid.Price))
        Trace("Calculating a price that above the market by 10 tick sizes")
        buyOrderPrice = bestBid.Price - 10 * instrument.TickSize
        Trace("It is {}".format(buyOrderPrice))

        Trace("Create buy limit order")
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))

        Trace("Mark the order as manually placed")
        buyOrder.Manual = True

        Trace("Place 'manual' order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")
        self.eventOrderPlaced.clear()

        Trace("Create another buy limit order")
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))

        buyOrder.MiFIDAlgorithmID = "My-Own-MiFID-Algo-ID"
        Trace("Set MiFID algorithm ID to {}".format(buyOrder.MiFIDAlgorithmID))
        Trace(
            "Setting MiFID algo ID automatically makes it 'non-manual'. Is it manual? : {}"
            .format(buyOrder.Manual))

        Trace("Place the 'non-manual' aka 'algo' order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account (it should be authorized to trade {})".
              format(SYMBOL))
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("{} instrument requesting...".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("{} instrument waiting...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")
        instrument = win32com.client.Dispatch(self.instrument)

        offsetCount = instrument.DiscretionaryOffsetCount
        Trace("Symbol {} has {} discretionary offset count".format(
            instrument.FullName, offsetCount))

        AssertMessage(
            offsetCount != 0,
            "Symbol does not have discretionary prices. Select another one.")

        bestBid = instrument.Bid
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set an order price due to invalid BBA")

        Trace("Best bid value is {}".format(bestBid.Price))
        Trace("Calculating a price that below the market by 10 tick sizes")
        buyOrderPrice = bestBid.Price - 10 * instrument.TickSize
        Trace("It is {}".format(buyOrderPrice))
        Trace("Create Buy limit order")
        buyOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateOrder(constants.otLimit,
                                                   self.instrument,
                                                   self.account, 1,
                                                   constants.osdUndefined,
                                                   buyOrderPrice))
        Trace("Set discretionary offset for the order price")
        buyOrder.DiscretionaryOffset = offsetCount - 1
        properties = win32com.client.Dispatch(buyOrder.Properties)
        executionInstructions = properties(constants.opExecutionInstructions)
        executionInstructions.Value = constants.oeiDiscretion

        Trace("Place order")
        buyOrder.Place()
        Trace("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT),
                      "Order placing timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")
Example #16
0
    def Start(self):
        Trace("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        Trace("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT),
                      "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        Trace("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT),
                      "Accounts coming timeout!")

        Trace("Select the first account")
        accounts = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.Accounts)
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        Trace("Requesting instrument {}".format(SYMBOL))
        self.celEnvironment.cqgCEL.NewInstrument(SYMBOL)
        Trace("Waiting for instrument {} ...".format(SYMBOL))
        AssertMessage(self.eventInstrumentIsReady.wait(TIMEOUT),
                      "Instrument resolution timeout!")

        instrument = win32com.client.Dispatch(self.instrument)

        bestBid = instrument.Bid
        AssertMessage(bestBid.IsValid,
                      "Error! Can't set a fill price due to invalid BBA")

        Trace("Best bid value is {}".format(bestBid.Price))
        Trace("Calculating a price that above the market by 10 tick sizes")
        buyOrderPrice = bestBid.Price - 10 * instrument.TickSize
        Trace("It is {}".format(buyOrderPrice))

        statementTime = datetime.now(timezone.utc)

        Trace("Creating a request for manual fill adding and fill it")
        manualFillRequest = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateManualFillRequest(
                constants.mfutAdd, None))
        manualFillRequest.GWAccountID = self.account.GWAccountID
        manualFillRequest.InstrumentName = instrument.FullName
        manualFillRequest.Note = "Hi from API!"
        manualFillRequest.Price = buyOrderPrice
        manualFillRequest.Quantity = 1
        manualFillRequest.Side = constants.osdUndefined
        manualFillRequest.StatementDate = statementTime
        manualFillRequest.TradeTimestamp = statementTime
        manualFillRequest.SpeculationType = constants.sptSpeculation

        Trace("Invoking the request")
        self.celEnvironment.cqgCEL.RequestManualFillUpdate(manualFillRequest)

        Trace("Waiting for manual fill adding...")
        AssertMessage(self.eventManualFillUpdateResolved.wait(TIMEOUT),
                      "Manual fill adding timeout!")

        Trace("Requesting manual fills for account {}".format(
            self.account.GWAccountID))
        self.celEnvironment.cqgCEL.RequestManualFills(self.account.GWAccountID,
                                                      constants.mfdlSnapshot)

        Trace("Waiting for manual fills receiving...")
        AssertMessage(self.eventManualFillsResolved.wait(TIMEOUT),
                      "Manual fills receiving timeout!")

        Trace("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT),
                      "GW disconnection timeout!")

        Trace("Done!")