/*abstract*/ public void runStrategy(IWebSocketClientConnection webSocketConnection, string symbol) { // Run the strategy to try to have an order on at least one side of the book according to fixed price range // but never executing as a taker if (!_enabled) // strategy cannot run when disabled { LogStatus(LogStatusType.WARN, "Strategy is disabled and will not run"); return; } // ** temporary workaround to support market pegged sell order strategy without plugins** if (_priceType == PriceType.PEGGED && _strategySide == OrderSide.SELL) { // make the price float according to the MID Price /* * // requires the Security List for the trading symbol * SecurityStatus status = _tradeclient.GetSecurityStatus ("BLINK", symbol); * if (status == null) * { * LogStatus( * LogStatusType.WARN, * String.Format( * "Waiting Security Status BLINK:{0} to run Pegged strategy", * symbol) * ); * return; * } */ // check the remaining qty that can still be sold ulong theSoldAmount = _tradeclient.GetSoldAmount(); if (theSoldAmount < _maxAmountToSell) { ulong uAllowedAmountToSell = _maxAmountToSell - theSoldAmount; _maxTradeSize = _maxTradeSize < uAllowedAmountToSell ? _maxTradeSize : uAllowedAmountToSell; _maxTradeSize = _maxTradeSize > _minTradeSize ? _maxTradeSize : _minTradeSize; } else { LogStatus(LogStatusType.WARN, String.Format("[runStrategy] Cannot exceed the allowed max amount to sell : {0} {1}", theSoldAmount, _maxAmountToSell)); _tradeclient.CancelOrderByClOrdID(webSocketConnection, _strategySellOrderClorid); return; } // gather the data to calculate the midprice OrderBook orderBook = _tradeclient.GetOrderBook(symbol); // instead of bestAsk let's use the Price reached if one decides to buy 1 BTC ulong maxPriceToBuy1BTC = orderBook.MaxPriceForAmountWithoutSelfOrders( OrderBook.OrdSide.SELL, (ulong)(1 * 1e8), // TODO: make it a parameter _tradeclient.UserId); // gather the magic element of the midprice (i.e. price to buy 10 BTC) ulong maxPriceToBuyXBTC = orderBook.MaxPriceForAmountWithoutSelfOrders( OrderBook.OrdSide.SELL, (ulong)(10 * 1e8), // TODO: make it a parameter _tradeclient.UserId); // instead of the last price let's use the VWAP (short period tick based i.e last 30 min.) ulong vwap = _tradeclient.CalculateVWAP(); ulong lastPx = _tradeclient.GetLastPrice(); ulong marketPrice = vwap > lastPx ? vwap : lastPx; // calculate the mid price //ulong midprice = (ulong)((status.BestAsk + status.BestBid + status.LastPx + maxPriceToBuyXBTC) / 4); ulong midprice = (ulong)((orderBook.BestBid.Price + maxPriceToBuy1BTC + maxPriceToBuyXBTC + marketPrice) / 4); Debug.Assert(_pegOffsetValue > 0); _sellTargetPrice = midprice + _pegOffsetValue; // get the dollar price SecurityStatus usd_official_quote = _tradeclient.GetSecurityStatus("UOL", "USDBRL"); // use USDBRT for the turism quote if (usd_official_quote == null || usd_official_quote.BestAsk == 0) { LogStatus(LogStatusType.WARN, "UOL:USDBRL not available"); } // get the BTC Price in dollar SecurityStatus bitfinex_btcusd_quote = _tradeclient.GetSecurityStatus("BITSTAMP", "BTCUSD"); if (bitfinex_btcusd_quote == null || bitfinex_btcusd_quote.BestAsk == 0) { LogStatus(LogStatusType.WARN, "BITSTAMP:BTCUSD not available"); } // calculate the selling floor must be at least the price of the BTC in USD //ulong floor = (ulong)(1.01 * bitfinex_btcusd_quote.BestAsk * (float)(usd_official_quote.BestAsk / 1e8)); //if (floor == 0) { ulong floor = (ulong)(8900 * 1e8); // TODO: make it an optional parameter or pegged to the dolar bitcoin //} //floor = (ulong)(5400 * 1e8); // check the selling FLOOR if (_sellTargetPrice < floor) { _sellTargetPrice = floor; } } // run the strategy if (_maxTradeSize > 0) { webSocketConnection.EnableTestRequest = false; if (_strategySide == OrderSide.BUY || _strategySide == default(char)) // buy or both { runBuyStrategy(webSocketConnection, symbol); } if (_strategySide == OrderSide.SELL || _strategySide == default(char)) // sell or both { runSellStrategy(webSocketConnection, symbol); } webSocketConnection.EnableTestRequest = true; } }
private void runSellStrategy(IWebSocketClientConnection webSocketConnection, string symbol) { OrderBook.IOrder bestOffer = _tradeclient.GetOrderBook(symbol).BestOffer; if (bestOffer != null) { if (bestOffer.UserId != _tradeclient.UserId) { // sell @ 1 cent bellow the best price (TODO: parameter for price increment) ulong sellPrice = bestOffer.Price - (ulong)(0.01 * 1e8); if (sellPrice >= _sellTargetPrice) { replaceOrder(webSocketConnection, symbol, OrderSide.SELL, sellPrice); } else { // cannot fight for the first position thus try to find a visible position in the book OrderBook orderBook = _tradeclient.GetOrderBook(symbol); List <OrderBook.Order> sellside = orderBook.GetOfferOrders(); int i = sellside.BinarySearch( new OrderBook.Order(OrderBook.OrdSide.SELL, _sellTargetPrice + (ulong)(0.01 * 1e8)), new OrderBook.OrderPriceComparer() ); int position = (i < 0 ? ~i : i); Debug.Assert(position > 0); // verificar se a profundidade vale a pena: (TODO: parameters for max_pos_depth and max_amount_depth) if (position > 5 + 1 && orderBook.DoesAmountExceedsLimit( OrderBook.OrdSide.SELL, position - 1, (ulong)(10 * 1e8))) { _tradeclient.CancelOrderByClOrdID(webSocketConnection, _strategySellOrderClorid); return; } var pivotOrder = sellside[position]; if (pivotOrder.UserId == _tradeclient.UserId) { // ordem ja e minha : pega + recursos disponiveis e cola no preco no vizinho se já nao estiver ulong price_delta = sellside[position + 1].Price - pivotOrder.Price; ulong newSellPrice = (price_delta > (ulong)(0.01 * 1e8) ? pivotOrder.Price + price_delta - (ulong)(0.01 * 1e8) : pivotOrder.Price); ulong availableQty = calculateOrderQty(symbol, OrderSide.SELL); if (newSellPrice > pivotOrder.Price || availableQty > pivotOrder.Qty) { replaceOrder(webSocketConnection, symbol, OrderSide.SELL, newSellPrice, availableQty); } } else { // estabelece preco de venda 1 centavo menor do que nesta posicao ulong newSellPrice = pivotOrder.Price - (ulong)(0.01 * 1e8); replaceOrder(webSocketConnection, symbol, OrderSide.SELL, newSellPrice); } } } else { // check and replace the order to get closer to the order in the second position and gather more available funds List <OrderBook.Order> sellside = _tradeclient.GetOrderBook(symbol).GetOfferOrders(); ulong price_delta = sellside.Count > 1 ? sellside[1].Price - sellside[0].Price : 0; ulong newSellPrice = (price_delta > (ulong)(0.01 * 1e8) ? bestOffer.Price + price_delta - (ulong)(0.01 * 1e8) : bestOffer.Price); ulong availableQty = calculateOrderQty(symbol, OrderSide.SELL); if (newSellPrice > bestOffer.Price || availableQty > bestOffer.Qty) { replaceOrder(webSocketConnection, symbol, OrderSide.SELL, newSellPrice, availableQty); } } } else { // TODO: empty book scenario } }
private void OnBrokerNotification(object sender, SystemEventArgs evt) { IWebSocketClientConnection webSocketConnection = (IWebSocketClientConnection)sender; try { switch (evt.evtType) { case SystemEventType.LOGIN_OK: LogStatus(LogStatusType.INFO, "Processing after succesful LOGON"); this._myUserID = evt.json["UserID"].Value <ulong>(); // disable test request to avoid disconnection during the "slow" market data processing webSocketConnection.EnableTestRequest = false; StartInitialRequestsAfterLogon(webSocketConnection); break; case SystemEventType.MARKET_DATA_REQUEST_REJECT: LogStatus(LogStatusType.ERROR, "Unexpected Marketdata Request Reject"); webSocketConnection.Shutdown(); break; case SystemEventType.MARKET_DATA_FULL_REFRESH: { string symbol = evt.json["Symbol"].Value <string>(); // dump the order book LogStatus(LogStatusType.WARN, _allOrderBooks[symbol].ToString()); // bring back the testrequest keep-alive mechanism after processing the book webSocketConnection.EnableTestRequest = true; // run the trading strategy to buy and sell orders based on the top of the book _tradingStrategy.runStrategy(webSocketConnection, symbol); // TODO: remove the temp dump bellow this._vwapForTradingSym.PrintTradesAndTheVWAP(); // example how to notify the application to start //this._tradingStrategy.OnStart(webSocketConnection); } break; // --- Order Book Management Events --- case SystemEventType.ORDER_BOOK_CLEAR: { string symbol = evt.json["Symbol"].Value <string>(); OrderBook orderBook = null; if (_allOrderBooks.TryGetValue(symbol, out orderBook)) { orderBook.Clear(); } else { orderBook = new OrderBook(symbol); _allOrderBooks.Add(symbol, orderBook); } } break; case SystemEventType.ORDER_BOOK_NEW_ORDER: { string symbol = evt.json["Symbol"].Value <string>(); OrderBook orderBook = null; if (_allOrderBooks.TryGetValue(symbol, out orderBook)) { orderBook.AddOrder(evt.json); } else { LogStatus(LogStatusType.ERROR, "Order Book not found for Symbol " + symbol + " @ " + evt.evtType.ToString()); } } break; case SystemEventType.ORDER_BOOK_DELETE_ORDERS_THRU: { string symbol = evt.json["Symbol"].Value <string>(); OrderBook orderBook = null; if (_allOrderBooks.TryGetValue(symbol, out orderBook)) { orderBook.DeleteOrdersThru(evt.json); } else { LogStatus(LogStatusType.ERROR, "Order Book not found for Symbol " + symbol + " @ " + evt.evtType.ToString() ); } } break; case SystemEventType.ORDER_BOOK_DELETE_ORDER: { string symbol = evt.json["Symbol"].Value <string>(); OrderBook orderBook = null; if (_allOrderBooks.TryGetValue(symbol, out orderBook)) { orderBook.DeleteOrder(evt.json); } else { LogStatus(LogStatusType.ERROR, "Order Book not found for Symbol " + symbol + " @ " + evt.evtType.ToString() ); } } break; case SystemEventType.ORDER_BOOK_UPDATE_ORDER: { string symbol = evt.json["Symbol"].Value <string>(); OrderBook orderBook = null; if (_allOrderBooks.TryGetValue(symbol, out orderBook)) { orderBook.UpdateOrder(evt.json); } else { LogStatus(LogStatusType.ERROR, "Order Book not found for Symbol " + symbol + " @ " + evt.evtType.ToString() ); } } break; // ------------------------------------ case SystemEventType.TRADE_CLEAR: LogStatus(LogStatusType.WARN, "Receieved Market Data Event " + evt.evtType.ToString()); break; case SystemEventType.SECURITY_STATUS: { LogStatus(LogStatusType.WARN, "Receieved Market Data Event " + evt.evtType.ToString() + " " + (evt.json != null ? evt.json.ToString() : ".") ); SecurityStatus securityStatus = new SecurityStatus(); securityStatus.Market = evt.json["Market"].Value <string>(); securityStatus.Symbol = evt.json["Symbol"].Value <string>(); securityStatus.LastPx = evt.json["LastPx"].Value <ulong>(); securityStatus.HighPx = evt.json["HighPx"].Value <ulong>(); if (evt.json["BestBid"].Type != JTokenType.Null) { securityStatus.BestBid = evt.json["BestBid"].Value <ulong>(); } else { securityStatus.BestBid = 0; } if (evt.json["BestAsk"].Type != JTokenType.Null) { securityStatus.BestAsk = evt.json["BestAsk"].Value <ulong>(); } else { securityStatus.BestAsk = 0; } if (evt.json["LowPx"].Type != JTokenType.Null) { securityStatus.LowPx = evt.json["LowPx"].Value <ulong>(); } else { securityStatus.LowPx = 0; } securityStatus.SellVolume = evt.json["SellVolume"].Value <ulong>(); securityStatus.BuyVolume = evt.json["BuyVolume"].Value <ulong>(); // update the security status information string securityKey = securityStatus.Market + ":" + securityStatus.Symbol; _securityStatusEntries[securityKey] = securityStatus; // update the strategy when a new market information arrives _tradingStrategy.runStrategy(webSocketConnection, _tradingSymbol); } break; case SystemEventType.TRADE: { JObject msg = evt.json; LogStatus(LogStatusType.WARN, "Receieved Market Data Event " + evt.evtType.ToString() + msg); _vwapForTradingSym.pushTrade( new ShortPeriodTickBasedVWAP.Trade( msg["TradeID"].Value <ulong>(), msg["Symbol"].Value <string>(), msg["MDEntryPx"].Value <ulong>(), msg["MDEntrySize"].Value <ulong>(), String.Format("{0} {1}", msg["MDEntryDate"].Value <string>(), msg["MDEntryTime"].Value <string>()) ) ); /* * LogStatus( * LogStatusType.INFO, * String.Format( * "New Trade : VWAP = {0} | LastPx = {1} - {2} | Size = {3}", * _vwapForTradingSym.calculateVWAP(), * _vwapForTradingSym.getLastPx(), * msg["MDEntryPx"].Value<ulong>(), * msg["MDEntrySize"].Value<ulong>() * ) * ); */ } break; case SystemEventType.TRADING_SESSION_STATUS: break; case SystemEventType.MARKET_DATA_INCREMENTAL_REFRESH: LogStatus(LogStatusType.WARN, "Receieved Market Data Incremental Refresh : " + evt.evtType.ToString()); // update the strategy when an incremental message is processed _tradingStrategy.runStrategy(webSocketConnection, _tradingSymbol); break; // --- Order Entry Replies --- case SystemEventType.EXECUTION_REPORT: { LogStatus(LogStatusType.WARN, "Receieved " + evt.evtType.ToString() + "\n" + evt.json.ToString()); MiniOMS.IOrder order = ProcessExecutionReport(evt.json); _tradingStrategy.OnExecutionReport(webSocketConnection, order); } break; case SystemEventType.ORDER_LIST_RESPONSE: { // process the requested list of orders JObject msg = evt.json; LogStatus(LogStatusType.WARN, "Received " + evt.evtType.ToString() + " : " + "Page=" + msg["Page"].Value <string>() ); JArray ordersLst = msg["OrdListGrp"].Value <JArray>(); if (ordersLst != null && ordersLst.Count > 0) { var columns = msg["Columns"].Value <JArray>(); Dictionary <string, int> indexOf = new Dictionary <string, int>(); int index = 0; foreach (JToken col in columns) { indexOf.Add(col.Value <string>(), index++); } foreach (JArray data in ordersLst) { MiniOMS.Order order = new MiniOMS.Order(); order.ClOrdID = data[indexOf["ClOrdID"]].Value <string>(); order.OrderID = data[indexOf["OrderID"]].Value <ulong>(); order.Symbol = data[indexOf["Symbol"]].Value <string>(); order.Side = data[indexOf["Side"]].Value <char>(); order.OrdType = data[indexOf["OrdType"]].Value <char>(); order.OrdStatus = data[indexOf["OrdStatus"]].Value <char>(); order.AvgPx = data[indexOf["AvgPx"]].Value <ulong>(); order.Price = data[indexOf["Price"]].Value <ulong>(); order.OrderQty = data[indexOf["OrderQty"]].Value <ulong>(); order.OrderQty = data[indexOf["LeavesQty"]].Value <ulong>(); order.CumQty = data[indexOf["CumQty"]].Value <ulong>(); order.CxlQty = data[indexOf["CxlQty"]].Value <ulong>(); order.Volume = data[indexOf["Volume"]].Value <ulong>(); order.OrderDate = data[indexOf["OrderDate"]].Value <string>(); order.TimeInForce = data[indexOf["TimeInForce"]].Value <char>(); LogStatus(LogStatusType.WARN, "Adding Order to MiniOMS -> ClOrdID = " + order.ClOrdID.ToString() + " OrdStatus = " + order.OrdStatus ); try { _miniOMS.AddOrder(order); } catch (System.ArgumentException) { } } // check and request the next page if (ordersLst.Count >= msg["PageSize"].Value <int>()) { LogStatus(LogStatusType.INFO, "Requesting Page " + msg["Page"].Value <int>() + 1); SendRequestForOpenOrders(webSocketConnection, msg["Page"].Value <int>() + 1); } else { LogStatus(LogStatusType.INFO, "EOT - no more Order List pages to process."); // notify application that all requestes where replied, // assuming the ORDER_LIST_REQUEST was the last in the StartInitialRequestsAfterLogon //_tradingStrategy.OnStart(webSocketConnection); } } } break; case SystemEventType.BALANCE_RESPONSE: if (evt.json != null) { //JObject receivedBalances = evt.json[_brokerId.ToString()].Value<JObject>(); foreach (var rb in evt.json[_brokerId.ToString()].Value <JObject>()) { try { this._balances[rb.Key] = rb.Value.Value <ulong>(); } catch (System.OverflowException) { // TODO: find a better solution for this kind of conversion problem // {"4": {"BRL_locked": -1, "BTC_locked": 0, "BRL": 48460657965, "BTC": 50544897}, "MsgType": "U3", "ClientID": 90826379, "BalanceReqID": 3} this._balances[rb.Key] = 0; } } // update the strategy when the balance is updated _tradingStrategy.runStrategy(webSocketConnection, _tradingSymbol); } break; case SystemEventType.TRADE_HISTORY_RESPONSE: { JObject msg = evt.json; LogStatus(LogStatusType.WARN, "Received " + evt.evtType.ToString() + " : " + "Page=" + msg["Page"].Value <string>() ); /* * JArray all_trades = msg["TradeHistoryGrp"].Value<JArray>(); * * if (all_trades != null && all_trades.Count > 0) * { * var columns = msg["Columns"].Value<JArray>(); * Dictionary<string, int> indexOf = new Dictionary<string, int>(); * int index = 0; * foreach (JToken col in columns) * { * indexOf.Add(col.Value<string>(), index++); * } * * foreach (JArray trade in all_trades) * { * _vwapForTradingSym.pushTrade( * new ShortPeriodTickBasedVWAP.Trade( * trade[indexOf["TradeID"]].Value<ulong>(), * trade[indexOf["Market"]].Value<string>(), * trade[indexOf["Price"]].Value<ulong>(), * trade[indexOf["Size"]].Value<ulong>(), * trade[indexOf["Created"]].Value<string>() * ) * ); * } * * // check and request the next page * if (all_trades.Count >= msg["PageSize"].Value<int>()) * { * LogStatus(LogStatusType.INFO, "TODO: Requesting Page " + msg["Page"].Value<int>() + 1); * //TODO: create a function to call here and request a new page if requested period in minutes is not satified * } * else * { * LogStatus(LogStatusType.INFO, "EOT - no more Trade History pages to process."); * } * * LogStatus(LogStatusType.INFO, String.Format("VWAP = {0}", _vwapForTradingSym.calculateVWAP())); * } */ } // break; case SystemEventType.CLOSED: // notify the application the connection was broken //_tradingStrategy.OnClose(webSocketConnection); break; // Following events are ignored because inheritted behaviour is sufficient for this prototype case SystemEventType.OPENED: case SystemEventType.ERROR: case SystemEventType.LOGIN_ERROR: case SystemEventType.HEARTBEAT: break; default: LogStatus(LogStatusType.WARN, "Unhandled Broker Notification Event : " + evt.evtType.ToString()); break; } } catch (Exception ex) { LogStatus(LogStatusType.ERROR, " OnBrokerNotification Event Handler Error : " + ex.Message.ToString() + "\n" + ex.StackTrace ); } }