Пример #1
0
        public void Init(Broker broker)
        {
            Broker = broker;
            if (broker == Broker.IB)
            {
                if (IBClient != null)
                {
                    Disconnect();
                    Thread.Sleep(500);
                }

                signal   = new EReaderMonitorSignal();
                IBClient = new IBClient(signal);

                IBClient.OpenOrder        += HandleOpenOrderMsg;
                IBClient.ExecutionDetails += HandleExecutionMsg;
                IBClient.OrderStatus      += HandleOrderStatusMsg;
            }
            else if (broker == Broker.TD)
            {
                TDClient = TDClient.Instance;
                TDClient.ExecutionDetails += HandleExecutionMsg;
                TDClient.OrderStatus      += HandleOrderStatusMsg;
            }

            IsInitialized = true;
        }
Пример #2
0
        public void connectAsync()
        {
            bool result = false;
            EReaderMonitorSignal signal_ = new EReaderMonitorSignal();

            Wotan.client client_ = null;
            EReader      reader_ = null;

            client_ = new Wotan.client(
                signal_,
                new dispatchDelegate((twsMessage m) =>
            {
                result = true;
            }),
                new logDelegate((string m, logType l, verbosity v, int id) => { }), true);

            reader_ = new EReader(client_.socket, signal_);
            reader_.Start();
            client_.connectAck();

            Thread.Sleep(1000);
            new Thread(() =>
            {
                while (client_.socket.IsConnected())
                {
                    signal_.waitForSignal();
                    reader_.processMsgs();
                }
            })
            {
                Name = "reading thread", IsBackground = true
            }.Start();

            Thread.Sleep(10000);
        }
Пример #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TwsObjectFactory"/> class.
        /// </summary>
        public TwsObjectFactory()
        {
            this.TwsCallbackHandler = new TwsCallbackHandler();

            this.signal       = new EReaderMonitorSignal();
            this.ClientSocket = new TwsClientSocket(new EClientSocket(this.TwsCallbackHandler, this.signal));
        }
Пример #4
0
        public void connectSync()
        {
            EReaderMonitorSignal signal_ = new EReaderMonitorSignal();

            Wotan.client client_ = new Wotan.client(signal_, new dispatchDelegate((twsMessage m) => {}),
                                                    new logDelegate((string m, logType l, verbosity v, int id) => { }), false);

            if (!client_.socket.IsConnected())
            {
                client_.socket.eConnect("127.0.0.1", 4001, 0);
                EReader reader = new EReader(client_.socket, signal_);
                reader.Start();

                new Thread(() =>
                {
                    while (client_.socket.IsConnected())
                    {
                        signal_.waitForSignal();
                        reader.processMsgs();
                    }
                })
                {
                    Name = "reading thread", IsBackground = true
                }.Start();

                Thread.Sleep(1000);
                client_.socket.eDisconnect();
            }
        }
Пример #5
0
 /// <summary>
 /// Connect
 /// </summary>
 /// <param name="host"></param>
 /// <param name="portIb"></param>
 /// <param name="clientIdIb"></param>
 public void Connect(string host, int portIb, int clientIdIb)
 {
     if (!IsConnectedIb)
     {
         try
         {
             ClientSocket.eConnect(host, portIb, clientIdIb);
             var signal = new EReaderMonitorSignal();
             var reader = new EReader(ClientSocket, signal);
             reader.Start();
             new Thread(() =>
             {
                 while (ClientSocket.IsConnected())
                 {
                     signal.waitForSignal();
                     reader.processMsgs();
                 }
             })
             {
                 IsBackground = true
             }.Start();
         }
         catch (Exception)
         {
             throw;
         }
     }
     else
     {
         IsConnectedIb = false;
         ClientSocket.eDisconnect();
     }
 }
Пример #6
0
 public client(EReaderMonitorSignal reader, dispatchDelegate dispatch, logDelegate log, bool aSync = true)
 {
     log_      = log;
     dispatch_ = dispatch;
     socket_   = new EClientSocket(this, reader)
     {
         AsyncEConnect = aSync
     };
 }
Пример #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TwsObjectFactory"/> class.
        /// </summary>
        /// <param name="host">The host</param>
        /// <param name="port">The port</param>
        /// <param name="clientId">The client id</param>
        public TwsObjectFactory(string host, int port, int clientId)
        {
            this.TwsCallbackHandler = new TwsCallbackHandler();

            this.signal       = new EReaderMonitorSignal();
            this.ClientSocket = new TwsClientSocket(new EClientSocket(this.TwsCallbackHandler, this.signal));

            this.TwsControllerBase = new TwsControllerBase(this.ClientSocket, this.TwsCallbackHandler, host, port, clientId);
            this.TwsController     = new TwsController(this.TwsControllerBase);
        }
        public static IBClient CreateNew(TimeSpan timeout)
        {
            var signal               = new EReaderMonitorSignal();
            var messageHandler       = new MessageHandler();
            var clientSocket         = new EClientSocket(messageHandler, signal);
            var clientCommandAsync   = new ClientCommandAsync(clientSocket, messageHandler, timeout);
            var manualResetEventSlim = new ManualResetEventSlim();

            return(new IBClient(signal, clientSocket, clientCommandAsync, messageHandler, manualResetEventSlim));
        }
Пример #9
0
        public IbClient(RequestsClient client, MyAppSettings settings)
        {
            Client = client;

            Signal        = new EReaderMonitorSignal();
            ClientSocket  = new EClientSocket(this, Signal);
            AccountNumber = settings.AccountNumber;
            AccountID     = settings.AccountID;
            InstrumentID  = settings.InstrumentID;
        }
Пример #10
0
        public client(IActorRef correlationManager, IActorRef logger)
        {
            // actors
            logger_             = logger;
            correlationManager_ = correlationManager;
            dispatcher_         = Context.ActorOf(dispatcher.Props(logger_), "clientActor");

            // tws components
            signal_ = new EReaderMonitorSignal();
            client_ = new Wotan.client(signal_, new dispatchDlg(dispatch), new logDlg(log), aSync: false);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TwsConnectionController"/> class.
 /// Controls the connection to TWS.
 /// </summary>
 /// <param name="clientSocket">The client socket</param>
 /// <param name="twsCallbackHandler">The callback handler</param>
 /// <param name="host">The host name</param>
 /// <param name="port">The port</param>
 /// <param name="clientId">The client ID, see TWS docs</param>
 public TwsConnectionController(
     ITwsClientSocket clientSocket,
     ITwsCallbackHandler twsCallbackHandler,
     string host,
     int port,
     int clientId)
 {
     this.clientSocket       = clientSocket;
     this.twsCallbackHandler = twsCallbackHandler;
     this.signal             = new EReaderMonitorSignal();
     this.host      = host;
     this.port      = port;
     this.clientId  = clientId;
     this.connected = false;
 }
Пример #12
0
        public Form1()
        {
            InitializeComponent();

            // listView1 setup
            listView1.View      = View.Details;
            listView1.GridLines = true;             // Horizoltal lines
            listView1.Columns.Add("Time:");
            listView1.Columns[0].Width = 60;
            listView1.Columns.Add("Source:", -2, HorizontalAlignment.Left);
            listView1.Columns.Add("Message:");
            listView1.Columns[2].Width = 400;

            // listView2 setup
            listView2.View      = View.Details;
            listView2.GridLines = true;             // Horizoltal lines
            listView2.Columns.Add("Time:");
            listView2.Columns[0].Width = 60;
            listView2.Columns.Add("Source:", -2, HorizontalAlignment.Left);
            listView2.Columns.Add("Message:");
            listView2.Columns[2].Width = 400;

            // IB API instances
            signal     = new EReaderMonitorSignal();
            ibClient   = new IBClient(signal);
            apiManager = new ApiManager(ibClient);

            // Trade messages parser
            parser = new Parser(this);

            // Events
            ibClient.CurrentTime    += IbClient_CurrentTime;    // Exchange current time
            ibClient.MarketDataType += IbClient_MarketDataType; // Request market data type callback (Delaed, Frozen etc.)
            ibClient.Error          += IbClient_Error;          // Errors handling
            ibClient.TickPrice      += IbClient_TickPrice;      // reqMarketData
            ibClient.NextValidId    += IbClient_NextValidId;    // Fires when api is connected (connect button clicked)
            ibClient.OrderStatus    += IbClient_OrderStatus;    // Order status
        }
Пример #13
0
 IbClient(EReaderMonitorSignal signal) : base(signal)
 {
 }
Пример #14
0
        public Form1()
        {
            InitializeComponent();

            // listView1 setup
            listView1.View          = View.Details;    // Shows the header
            listView1.FullRowSelect = true;            // !!!Lets to select the whole row in the table!!!

            // listView2 setup
            listView2.View      = View.Details;
            listView2.GridLines = true;             // Horizoltal lines
            listView2.Columns.Add("Time:");
            listView2.Columns[0].Width = 60;
            listView2.Columns.Add("Source:", -2, HorizontalAlignment.Left);
            listView2.Columns.Add("Message:");
            listView2.Columns[2].Width = 400;

            // DB log messages
            Log.InitializeDB();                                 // Connect to the database
            logThread = new Thread(new ThreadStart(LogThread)); // Make an instance of the thread and assign method name which will be executed in the thread

            // Basket thread
            executeBasketThread = new Thread(new ThreadStart(ExecuteBasketThread));

            // IB API instances
            signal     = new EReaderMonitorSignal();
            ibClient   = new IBClient(signal);
            apiManager = new ApiManager(ibClient, this);

            // Json search object class instance
            searchResponse         = new SearchResponse();
            quoteResponse          = new QuoteResponse();
            availableFundsResponse = new AvailableFundsResponse();

            // Fleck socket server
            FleckLog.Level = LogLevel.Debug;
            allSockets     = new List <IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:8181");

            // Other
            basket = new Basket(this, ibClient);

            server.SupportedSubProtocols = new[] { "superchat", "chat" };
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {;
                 Log.Insert(DateTime.Now, "Form1.cs", string.Format("Websocket connection open!"), "white");
                 allSockets.Add(socket); };
                socket.OnClose = () =>
                {
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    // Output message to system log
                    Log.Insert(DateTime.Now, "Form1.cs", string.Format("socket.OnMessage. A message received from a client: {0}", message), "white");
                    //allSockets.ToList().ForEach(s => s.Send("Hello from websocket! Form1.cs line 95")); // Send a greeting message to all websocket clients


                    // DETERMINE WHAT TYPE OF API REQUEST IS RECEVIED HERE
                    // apiManager.Search
                    // apiManager.GetQuote

                    var jsonObject  = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var requestBody = jsonObject["body"];

                    switch (jsonObject["requestType"].ToString())
                    {
                    case "symbolSearch":
                        apiManager.Search(requestBody["symbol"].ToString());
                        break;

                    case "getQuote":
                        apiManager.GetQuote(requestBody["symbol"].ToString(), (int)requestBody["basketNumber"], requestBody["currency"].ToString());
                        break;

                    case "getAvailableFunds":
                        ibClient.ClientSocket.reqAccountUpdates(true, "U2314623");
                        break;
                    }
                };
            });

            // Events
            ibClient.CurrentTime += IbClient_CurrentTime;               // Get exchnage current time
            // ibClient.MarketDataType += IbClient_MarketDataType;
            ibClient.Error += IbClient_Error;                           // Errors handling

            ibClient.TickPrice   += IbClient_TickPrice;                 // reqMarketData. EWrapper Interface
            ibClient.OrderStatus += IbClient_OrderStatus;               // Status of a placed order

            ibClient.NextValidId        += IbClient_NextValidId;        // Fires when api is connected. Connection status received here
            ibClient.ContractDetails    += IbClient_ContractDetails;    // Ticker search
            ibClient.ContractDetailsEnd += IbClient_ContractDetailsEnd; // Fires up when the the search response feed is finished. One search request can contain multiple contracts
            ibClient.UpdateAccountValue += IbClient_UpdateAccountValue; // Account info
        }
Пример #15
0
 public TWSEWrapper()
 {
     ReaderSignal = new EReaderMonitorSignal();
     ClientSocket = new EClientSocket(this, ReaderSignal);
 }
 /*Port is usually 7496 for TWS, 7497 for paper Trading/demo account on TWS,
  *  4001 for IBGateway, 4002 for paper Trading account on IBGateway. The port can be
  *  changed on Settings.
  *  You can have up to 9 seperate connections to IB at a time by using different
  *  ClientId's.*/
 public EWrapperImpl()
 {
     Signal       = new EReaderMonitorSignal();
     ClientSocket = new EClientSocket(this, Signal);
 }
Пример #17
0
        static void Main(string[] args)
        {
            int      reqId = 0;
            Settings settings;

            try
            {
                settings = JsonConvert.DeserializeObject <Settings>(File.ReadAllText(@"settings.json"));
            }
            catch (Exception)
            {
                settings = new Settings();
                File.WriteAllText(@"settings.json", JsonConvert.SerializeObject(settings, Formatting.Indented));

                Console.WriteLine("Defaults have been saved to 'settings.json'");
                Console.ReadKey();
                return;
            }

            var cnx = new MySqlConnectionStringBuilder();

            cnx.UserID   = settings.username;
            cnx.Password = settings.password;
            cnx.Server   = settings.server;
            cnx.Port     = settings.port;

            MySqlTransaction tr = null;
            var mysql           = new MySqlConnection(cnx.ToString());

            mysql.Open();

            // Create MySQL database and tables
            Create(mysql);

            Console.Write("Symbol: ");
            string symbol = Console.ReadLine();

            Console.Write("Duration (days): ");
            int days = Convert.ToInt32(Console.ReadLine());

            Console.Write("Retrieve ticks [y/n]: ");
            bool retrieveTicks = (Console.ReadLine() == "y");

            Console.WriteLine();

            DateTime end   = DateTime.Now;
            DateTime start = end.AddDays(-days);

            var signal = new EReaderMonitorSignal();
            var client = new IBClient(signal);

            client.ClientSocket.eConnect(settings.TWS, settings.TWSPort, settings.ClientID);

            var c = new Contract();

            c.Currency = "USD";

            if (symbol.StartsWith("@"))
            {
                c.Symbol   = symbol.Replace("@", "");
                c.SecType  = "CONTFUT";
                c.Exchange = FuturesExchange(symbol);
            }
            else
            {
                c.Symbol      = symbol;
                c.Exchange    = "SMART";
                c.SecType     = "STK";
                c.PrimaryExch = "ISLAND";   // fixes ambiguity
            }

            var contracts = new List <ContractDetails>();

            client.ContractDetails += (ContractDetailsMessage msg) =>
            {
                contracts.Add(msg.ContractDetails);
            };

            client.ContractDetailsEnd += (ContractDetailsEndMessage) =>
            {
                if (contracts.Count == 0)
                {
                    Console.WriteLine("No contracts found for {0}", symbol);
                }
                else
                {
                    ContractDetails closest = null;

                    foreach (var cd in contracts)
                    {
                        // No date (not futures)
                        if (string.IsNullOrEmpty(cd.Contract.LastTradeDateOrContractMonth))
                        {
                            closest = cd;
                            break;
                        }

                        var dt1 = DateTime.ParseExact(cd.Contract.LastTradeDateOrContractMonth, "yyyyMMdd", CultureInfo.InvariantCulture);

                        // Skip the contract if there's only 5 days left
                        if ((dt1 - DateTime.Now).Days <= 5)
                        {
                            continue;
                        }

                        // Find the closest contract
                        if (closest == null || dt1 < DateTime.ParseExact(closest.Contract.LastTradeDateOrContractMonth, "yyyyMMdd", CultureInfo.InvariantCulture))
                        {
                            closest = cd;
                        }
                    }

                    if (closest == null)
                    {
                        Console.WriteLine("Contract not found for {0}", symbol);
                    }
                    else
                    {
                        // Store the symbol
                        Insert(mysql, symbol);

                        // Transaction for bulk inserting
                        tr = mysql.BeginTransaction();

                        c = closest.Contract;

                        // Request candles
                        client.ClientSocket.reqHistoricalData(reqId++, closest.Contract, end.ToString("yyyyMMdd HH:mm:ss"), string.Format("{0} D", days), "1 min", "TRADES", 0, 1, false, null);
                    }
                }
            };

            // Request contract data
            client.ClientSocket.reqContractDetails(reqId++, c);

            client.HistoricalData += (HistoricalDataMessage msg) =>
            {
                Insert(mysql, tr, symbol, 60, msg);
            };

            client.HistoricalDataEnd += (HistoricalDataEndMessage msg) =>
            {
                // Commit data
                tr.Commit();

                Console.WriteLine("Finished retrieving candles");

                if (retrieveTicks)
                {
                    // New transaction for ticks
                    tr = mysql.BeginTransaction();

                    // Request ticks
                    client.ClientSocket.reqHistoricalTicks(reqId++, c, null, end.ToString("yyyyMMdd HH:mm:ss"), 1000, "TRADES", 0, true, null);
                }
            };

            client.historicalTickLast += (int req, HistoricalTickLast[] ticks, bool done) =>
            {
                Insert(mysql, tr, symbol, ticks);

                if (done)
                {
                    end = UnixTimeStampToDateTime(ticks[0].Time);

                    if (end <= start)
                    {
                        // Commit data
                        tr.Commit();

                        Console.WriteLine("Finished retrieving ticks");
                    }
                    else
                    {
                        client.ClientSocket.reqHistoricalTicks(reqId++, c, null, end.ToString("yyyyMMdd HH:mm:ss"), 1000, "TRADES", 0, true, null);
                    }
                }
            };

            client.Error += (int id, int errorCode, string str, Exception ex) =>
            {
                if (id != -1)
                {
                    Console.WriteLine("{0} {1} {2} {3}", DateTime.Now, id, errorCode, str);
                }
            };

            var reader = new EReader(client.ClientSocket, signal);

            reader.Start();

            while (true)
            {
                signal.waitForSignal();
                reader.processMsgs();
            }
        }
Пример #18
0
        // interfaces
        public override void onStartImpl(string[] args)
        {
            if (launchGatewayProcess())
            {
                // connection attempt
                try
                {
                    var conf = (configuration)config_;

                    logger_ = conf.logger.create();
                    signal_ = new EReaderMonitorSignal();
                    corr_   = new correlationManager();

                    //dispatcher_ = new dis
                    // tws components
                    //client_ = new client(signal_, new dispatchDelegate(dispatch), new logDelegate(logger_.add), aSync: false);

                    // create the client
                    //client_ = actorSystem_.ActorOf(actors.client.Props(corr_, logger_), "clientActor");

                    //client_.Tell(new connect(config_.ibEnvironment.credentials.host, config_.ibEnvironment.credentials.port));

                    //// wait for the connection
                    //while (Task.Run(async () =>
                    //{
                    //    var t = client_.Ask<connectionStatus>(new connectionStatus(), TimeSpan.FromSeconds(10));
                    //    await t;
                    //    return t.Result.isConnected;
                    //}).Result != true)
                    //{
                    //    Thread.Sleep(100);
                    //}

                    //// add historical data manager
                    //hist_ = actorSystem_.ActorOf(actors.historicalDataManager.Props(client_, corr_, logger_), "historicalManagerActor");

                    //hist_.Tell(new actors.historicalDataManager.request(new Contract()
                    //{
                    //    Symbol = "SDS",
                    //    SecType = "STK",
                    //    Exchange = "SMART",
                    //    Currency = "USD"
                    //}, new DateTime(2016, 11, 27, 10, 28, 43),
                    //    TimeSpan.FromDays(10),
                    //    TimeSpan.FromDays(1),
                    //    actors.historicalDataManager.barType.MIDPOINT, 0, 1));
                }
                catch (Exception ex)
                {
                    logger_?.add("an error has occurred: " + ex.ToString(),
                                 logType.error, verbosity.high);
                }
            }
            else
            {
                logger_?.add("no running ibgateway process found, shutting down the service...",
                             logType.error, verbosity.high);

                Stop();
            }
        }
Пример #19
0
 public InteractiveBrokersApi()
 {
     Logger        = LogManager.GetLogger("IbApi");
     EReaderSignal = new EReaderMonitorSignal();
     Client        = new EClientSocket(this, EReaderSignal);
 }
Пример #20
0
 public MarketData()
 {
     _readerSignal = new EReaderMonitorSignal();
     _clientSocket = new EClientSocket(this, _readerSignal);
 }