Exemplo n.º 1
0
        public static OrderDetails GetLotSize(Tuple <bool, bool, int> db, OrderDetails orderDetails, Strategy strategy, SignalFile signalFile, Positions positions)
        {
            int signalDirection = signalFile.Signal;
            //int tradeDirection;

            int strategyCurrentPosition = db.Item3;

            //Trade direction
            //if (strategyCurrentPosition > 0 && signalDirection < 0)
            //{
            //    tradeDirection = -1;
            //}
            //else if (strategyCurrentPosition < 0 && signalDirection > 0)
            //{
            //    tradeDirection = 1;
            //}
            //else if (strategyCurrentPosition < 0 && signalDirection < 0)
            //{
            //    tradeDirection = -1;
            //}
            //else if (strategyCurrentPosition > 0 && signalDirection > 0)
            //{
            //    tradeDirection = 1;
            //}
            //else
            //{
            //    tradeDirection = signalFile.Signal;
            //}

            if (positions.IBSymbol == strategy.Symbol && signalFile.StrategyName == strategy.StrategyName)
            {
                switch (signalFile.Exit)
                {
                case "0":
                    if (strategyCurrentPosition > 0 && strategyCurrentPosition != 0 && signalDirection < 0)
                    {
                        orderDetails.LotSize = (strategy.LotSize * 2);
                    }
                    else if (strategyCurrentPosition < 0 && strategyCurrentPosition != 0 && signalDirection > 0)
                    {
                        orderDetails.LotSize = (strategy.LotSize * 2);
                    }
                    else if (strategyCurrentPosition != 0)
                    {
                        orderDetails.LotSize = strategy.LotSize;
                    }
                    else
                    {
                        orderDetails.LotSize = strategy.LotSize;
                    }
                    break;

                case "1":
                    //if (strategyCurrentPosition > 0 && signalDirection != tradeDirection)
                    //{
                    //    orderDetails.LotSize = strategy.LotSize;
                    //}
                    //else if (strategyCurrentPosition < 0 && signalDirection != tradeDirection)
                    //{
                    //    orderDetails.LotSize = strategy.LotSize;
                    //}
                    //else
                    //{
                    orderDetails.LotSize = strategy.LotSize;
                    //}
                    break;
                }
            }
            else if (string.IsNullOrEmpty(positions.IBSymbol) && strategyCurrentPosition == 0)
            {
                orderDetails.LotSize = strategy.LotSize;
            }

            GetOrderSide(signalFile, orderDetails);

            return(orderDetails);
        }
Exemplo n.º 2
0
        public static void CheckLastTrade(SignalFile signalFile, Transactions transactions, SimpleLogger log, Positions positions, Tuple <bool, bool, int> db)
        {
            if (db.Item1)
            {
                log.Warning($"Trying to Exceed Max Position. No order sent for {signalFile.Output}");
            }

            if (signalFile.Signal == 1 && transactions.LastTradeSide == 1 && positions.IBCurrentPosition > 0 && signalFile.StrategyName == transactions.Strategy)
            {
                log.Warning($"Last order sent in db was a BUY for {signalFile.Output}");
            }

            if (signalFile.Signal == -1 && transactions.LastTradeSide == -1 && positions.IBCurrentPosition < 0 && signalFile.StrategyName == transactions.Strategy)
            {
                log.Warning($"Last order sent in db was a SELL for {signalFile.Output}");
            }
        }
Exemplo n.º 3
0
 public Controller(EClientSocket clientSocket, SimpleLogger log, Parameters @params, Strategy strategy, Broker broker, Positions positions, FuturesContract futures, Prices prices, Transactions transactions, Slack slack)
 {
     this.@params      = @params;
     this.log          = log;
     this.clientSocket = clientSocket;
     this.strategy     = strategy;
     this.broker       = broker;
     this.futures      = futures;
     this.prices       = prices;
     this.transactions = transactions;
     this.slack        = slack;
 }
Exemplo n.º 4
0
        public Tuple <bool, bool, int> GetMaxPosition(Strategy strategy, SignalFile signalFile, Transactions transactions, Positions positions, SimpleLogger log, Parameters @params)
        {
            bool   MaxTradeFlag = true;
            bool   maxPosFlag;
            double _position;

            Tuple <bool, int> db = ComparePositionAtIBandDB(strategy, signalFile, positions, log, @params);

            bool   dbPosConflict           = db.Item1;
            int    strategyCurrentPosition = db.Item2;
            double calculatedMaxPosition;

            //Converting position to positive number to validate if the number exceeds the max number for the strategy maximum position(s)
            if (!dbPosConflict)
            {
                _position             = (strategyCurrentPosition < 0) ? -1 * strategyCurrentPosition : strategyCurrentPosition;
                calculatedMaxPosition = CalculateMaxPosition(_position, strategy, signalFile, transactions, log);
            }
            else
            {
                _position = (positions.IBCurrentPosition < 0) ? -1 * positions.IBCurrentPosition : positions.IBCurrentPosition;

                if (dbPosConflict)//if dbconflict then the position in the database must be incorrect and last trade was never filled
                {
                    if (positions.IBCurrentPosition > 0)
                    {
                        transactions.LastTradeSide = 1;
                    }
                    else if (positions.IBCurrentPosition < 0)
                    {
                        transactions.LastTradeSide = -1;
                    }

                    strategyCurrentPosition = positions.IBCurrentPosition;

                    log.Warning($"Positions conflict. Using IB Position for last trade side: {transactions.LastTradeSide}");
                }

                calculatedMaxPosition = CalculateMaxPosition(_position, strategy, signalFile, transactions, log);
            }

            if (calculatedMaxPosition > strategy.StrategyMaxPosition && calculatedMaxPosition >= strategy.MaxPositionForSymbol)
            {
                maxPosFlag = true;

                log.Warning($"{signalFile.StrategyName} is trying to Exceed Strategy Max Position of {strategy.StrategyMaxPosition}.");
            }
            else if (calculatedMaxPosition <= strategy.StrategyMaxPosition)
            {
                maxPosFlag = false;
            }
            else
            {
                maxPosFlag = false;
            }
            log.Warning($"{signalFile.StrategyName} dbPosConflict:{dbPosConflict} MaxTradeFlag:{MaxTradeFlag} calculatedMaxPosition:{calculatedMaxPosition} strategy.StrategyMaxPosition:{strategy.StrategyMaxPosition} strategy.MaxPositionForSymbol:{strategy.MaxPositionForSymbol}");

            if (signalFile.StrategyName == strategy.StrategyName && !maxPosFlag && strategyCurrentPosition != 0)
            {
                switch (signalFile.Signal)
                {
                case 1:
                    if (strategyCurrentPosition < 0)
                    {
                        MaxTradeFlag = false;
                    }
                    else if (strategyCurrentPosition > 0 && _position <= strategy.MaxPositionForSymbol)
                    {
                        MaxTradeFlag = false;
                    }
                    break;

                case -1:
                    if (strategyCurrentPosition > 0)
                    {
                        MaxTradeFlag = false;
                    }
                    else if (strategyCurrentPosition < 0 && _position <= strategy.MaxPositionForSymbol)
                    {
                        MaxTradeFlag = false;
                    }
                    break;
                }
            }
            else if (strategyCurrentPosition == 0)
            {
                MaxTradeFlag = false;
            }

            return(new Tuple <bool, bool, int>(MaxTradeFlag, dbPosConflict, strategyCurrentPosition));
        }
Exemplo n.º 5
0
        public Tuple <bool, int> ComparePositionAtIBandDB(Strategy strategy, SignalFile signalFile, Positions positions, SimpleLogger log, Parameters @params)
        {
            bool dbPosConflict = false;

            int dbPosition = DBFunctions.GetCurrentStrategyPositionFromDB(log, strategy);

            if (dbPosition != positions.IBCurrentPosition && signalFile.StrategyName == strategy.StrategyName)
            {
                string slackMsg = $"*[POSITION CONFLICT]* *{strategy.StrategyName}* curr_Strategy_Position table:*{dbPosition}* and IB:*{IBCurrentPosition}*";

                dbPosConflict = true;

                log.Warning(slackMsg);

                slack.SendMessageToSlack(slackMsg, @params);
            }
            return(new Tuple <bool, int>(dbPosConflict, dbPosition));
        }
Exemplo n.º 6
0
        public static Positions SetIBPosition(Strategy strategy, int strategyPosition, Positions positions)
        {
            positions.IBSymbol          = strategy.Symbol;
            positions.IBCurrentPosition = strategyPosition;

            return(positions);
        }
Exemplo n.º 7
0
        public void ValidateConnectionToBroker(Strategy strategy, Positions positions)
        {
            int count = 0;
            int n;

            if (clientSocket.IsConnected())
            {
                UpdateIBPositionList(strategy, positions);
            }
            else
            {
                EWrapperImpl ibClient = new EWrapperImpl();

                while (!clientSocket.IsConnected())
                {
                    try { clientSocket.eConnect("127.0.0.1", 7496, 100); } catch (Exception ex) { this.log.Trace(ex.Message.ToString()); }

                    if (clientSocket.IsConnected())
                    {
                        var reader = new EReader(clientSocket, ibClient.Signal);

                        reader.Start();

                        new Thread(() =>
                        {
                            while (clientSocket.IsConnected())
                            {
                                ibClient.Signal.waitForSignal();
                                reader.processMsgs();
                            }
                        })
                        {
                            IsBackground = true
                        }.Start();

                        GetNextValideOrderId(ibClient);
                    }

                    if (!clientSocket.IsConnected())
                    {
                        if (count < Ordinal.Length - 1)
                        {
                            n = count;
                        }
                        else
                        {
                            n = Ordinal.Length - 1;
                        }
                        log.Warning($"{count + 1}{Ordinal[n].ToString()} attempt could not connect to IBApi. Retry in {[email protected]} seconds.");
                        // this.log.Warning($"{count + 1} attempt could not connect to IBApi. Retry in {[email protected]} seconds.");

                        Thread.Sleep(TimeSpan.FromSeconds([email protected]));
                        count++;
                    }
                    if (count > [email protected])
                    {
                        this.log.Warning("Closing. Could not establish connection.");

                        slack.SendMessageToSlack("*Closing App... Could not Establish Connection to Broker.*", @params);

                        Environment.Exit(1);
                    }
                }
            }
        }
Exemplo n.º 8
0
        private void UpdateIBPositionList(Strategy strategy, Positions positions)
        {
            bool connectionOK = true;
            int  cnt          = 0;
            int  n;

            if (!string.IsNullOrEmpty(strategy.Symbol))
            {
                Positions.PositionList.Clear();

                Positions.PositionEndFlag = false;

                clientSocket.reqPositions();

                while (!Positions.PositionEndFlag)
                {
                    if (Positions.PositionEndFlag)
                    {
                        break;
                    }

                    if (!clientSocket.IsConnected())
                    {
                        ValidateConnectionToBroker(strategy, positions);
                    }

                    if (cnt >= @params.maxLoopCount)
                    {
                        connectionOK = false;
                        this.log.Warning("[IB WARNING] Could not update IB Positions.");
                        break;
                    }

                    if (cnt < Ordinal.Length - 1)
                    {
                        n = cnt;
                    }
                    else
                    {
                        n = Ordinal.Length - 1;
                    }
                    this.log.Warning($"Waiting for IB Positions to Update. {cnt + 1}{Ordinal[n].ToString()} try.");
                    cnt++;
                }

                if (connectionOK == false)
                {
                    TimeSpan time = DateTime.Now.TimeOfDay;

                    if (time > new TimeSpan(00, 00, 00) && time < new TimeSpan(08, 00, 00))
                    {
                        slack.SendMessageToSlack("*Connection to Broker must have been lost.*", @params);
                        Thread.Sleep((TimeSpan.FromSeconds(60)));
                        RestartProgram();
                    }
                    else
                    {
                        slack.SendMessageToSlack("*Connection to Broker must have been lost.*", @params);
                        RestartProgram();
                    }
                }
            }
        }