Ejemplo n.º 1
0
        public bool GetOpenPositions(Account A, string Symbol, int Count, string columns) //fix this
        {
            BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);

            Dictionary <string, string> Params = new Dictionary <string, string>();

            Params.Add("symbol", Symbol);
            Params.Add("columns", columns);
            Params.Add("count", Convert.ToString(Count));

            string TargetURI = "/position?filter=%7B%22symbol%22%3A%22" + Symbol + "%22%7D&columns=%5B%22lastValue%22%5D&count=1";

            string Result = bitmex.Query("GET", TargetURI, null, true, false);

            Console.WriteLine(Result);

            if (Result.Contains("error") == true)
            {
                //do stuff with e
                return(false);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 2
0
        public static bool PreventLiquidations(Account A, string Symbol)
        {
            bool isTracking = true;

            while (isTracking)
            {
                BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);

                Dictionary <string, string> Params = new Dictionary <string, string>();
                Params.Add("symbol", Symbol);
                Params.Add("columns", "[\"lastValue\", \"liquidationPrice\"]");
                Params.Add("count", Convert.ToString(1));

                string TargetURI = "/position?filter=%7B%22symbol%22%3A%22" + Symbol + "%22%7D&columns=%5B%22lastValue%22%2C%20%22liquidationPrice%22%5D&count=1";

                string Result = bitmex.Query("GET", TargetURI, null, true, false);
                Console.WriteLine(Result);

                int LiqIndex = Result.IndexOf("liquidationPrice:");

                double LiquidationPrice = Convert.ToDouble(Convert.ToString(LiqIndex) + "liquidationPrice:".Length);
                Console.WriteLine("Liquidation: " + LiquidationPrice);



                //calcaullate bsackout % price - ~60-70%


                return(true);
            }

            return(true);
        }
Ejemplo n.º 3
0
        private void Run(string[] args)
        {
            BitMEXApi bitmexx = new BitMEXApi(bitmexKeyX, bitmexSecretX);
            // var orderBook = bitmex.GetOrderBook("XBTUSD", 3);
            var orders = bitmexx.GetOrders();

            // var orders = bitmex.DeleteOrders();
            Console.WriteLine(orders);
            Buy(bitmexx);
            Read(bitmexx);
            Order(bitmexx);
            Trade(bitmexx);

            var quotex = bitmexx.CurrentQuote();

            Console.WriteLine("Current bidPrice " + quotex[0]["bidPrice"]);


            BitMEXApi bitmexy = new BitMEXApi(bitmexKeyY, bitmexSecretY);

            var quotey = bitmexy.CurrentQuote();

            Console.WriteLine("Current askPrice " + quotey[0]["askPrice"]);
            double a = double.Parse(quotey[0]["askPrice"]);
            double b = a + 10.0;
            int    c = 20;

            bitmexx.OrderX(a, b, c);
        }
Ejemplo n.º 4
0
        public async System.Threading.Tasks.Task <List <WalletDTO> > GetBitmexTransactions(int userId)
        {
            var keyList = await _keyRepo.GetKeysFromNameAsync("BitMEX", userId);

            var walletHistory = new List <Wallet>();

            foreach (ExchangeKey key in keyList)
            {
                BitMEXApi bitMEXApi = new BitMEXApi(key.Key, key.Secret);

                string temp = bitMEXApi.GetWalletHistory();

                var walletHistoryTemp = JsonConvert.DeserializeObject <List <BitMEXWalletHistory> >(temp);

                foreach (BitMEXWalletHistory transaction in walletHistoryTemp)
                {
                    Wallet tempTransaction = ConvertBitmexTransaction(transaction, key.ExchangeKeyId);

                    if (!await WalletHistoryExists(tempTransaction.ExchangeTransactionId))
                    {
                        await _genericRepo.AddAsync(tempTransaction);

                        walletHistory.Add(tempTransaction);
                    }
                }
            }

            var walletHistoryDTO = new List <WalletDTO>();

            foreach (Wallet transaction in walletHistory)
            {
                walletHistoryDTO.Add(ConvertTransaction(transaction));
            }
            return(walletHistoryDTO);
        }
Ejemplo n.º 5
0
        //Get all orders from the BitMEX exchange after a given date from a given user
        public async Task <List <Order> > GetBitMEXOrdersFromUserId(int userId, int portfolioId, DateTime dateFrom)
        {
            var exchangeKey = await _keyRepo.GetKeysFromNameAsync("BitMEX", userId);

            var orderList = new List <Order>();

            foreach (ExchangeKey key in exchangeKey)
            {
                BitMEXApi bitmex = new BitMEXApi(key.Key, key.Secret);

                string date = dateFrom.ToString("yyyy-MM-dd hh:mm:ss.fff");

                string temp = bitmex.GetOrders(date);

                if (!temp.Contains("error"))
                {
                    try
                    {
                        var BitMEXOrderList = JsonConvert.DeserializeObject <List <BitMEXOrder> >(temp, new JsonSerializerSettings {
                            NullValueHandling = NullValueHandling.Ignore
                        });
                        foreach (var BitMEXOrder in BitMEXOrderList)
                        {
                            Order order = ConvertBitMEXOrder(BitMEXOrder, userId);
                            orderList.Add(order);
                        }
                    }
                    catch
                    {
                        return(null);
                    }
                }
            }
            return(orderList);
        }
Ejemplo n.º 6
0
        public ExecutionReport UpdateOrder(Order order)
        {
            //We use the class that was provided by BitMex @https://github.com/BitMEX/api-connectors
            //Propper version for C++
            BitMEXApi api = new BitMEXApi(URL, ID, Secret);

            var param = new Dictionary <string, string>();

            //param["clOrdID"] = order.ClOrdId;
            param["orderID"]  = order.OrderId;
            param["orderQty"] = order.OrderQty.HasValue ? order.OrderQty.Value.ToString("0.########") : "0";
            if (order.Price.HasValue)
            {
                param["price"] = order.Price.Value.ToString("0.########");
            }

            string resp = api.Query("PUT", "/order", param, true);

            ExecutionReport report = JsonConvert.DeserializeObject <ExecutionReport>(resp);

            ExecutionReport beExecReport = MapExecutionReport(report);

            beExecReport.Order = order;

            return(beExecReport);
        }
Ejemplo n.º 7
0
        public bool GetOrders(Account A, string Symbol)
        {
            BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);
            string    orders = bitmex.GetOrders(Symbol);

            orders = orders.Remove(0, 1);

            string[] orderlist = orders.Split('}');

            foreach (string shit in orderlist)
            {
                string oneOrder = shit;
                oneOrder += "}";
                if (oneOrder[0] == ',')
                {
                    oneOrder = oneOrder.Remove(0, 1);
                }

                //Console.WriteLine(oneOrder);
                try
                {
                    var data = JsonConvert.DeserializeObject <Order>(oneOrder);
                    Console.WriteLine(data.orderID + " " + data.symbol + " " + data.side + " " + data.price);
                }
                catch
                {
                    Console.WriteLine("Finished parsing user's orders.");
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 8
0
 private void btnValidate_Click(object sender, EventArgs e)
 {
     if (chkConsent.Checked)
     {
         try
         {
             bool RealNetwork = (Properties.Settings.Default.Network == "Real"); // Set the bool = true if the setting is real network, false if test
             bitmex = new BitMEXApi(txtKey.Text.Trim(), txtSecret.Text.Trim(), RealNetwork);
             GetAPIValidity();
             if (APIValid)
             {
                 this.Hide();
             }
         }
         catch (Exception ex)
         {
             // If it shoots an error, API is invalid.
             APIValid          = false;
             lblAPIStatus.Text = "API info is invalid!";
         }
     }
     else
     {
         MessageBox.Show("Please acknowledge the risks of using this application and accept responsibility for trades made by the application if you wish to continue.  \n\nDo this by reading the warning on the API Info form and checking the box under the warning that is followed by ''I understand'' if you acknowledge the risks and accept responsibility for trades made with the application.");
     }
 }
Ejemplo n.º 9
0
        private void button1_Click(object sender, EventArgs e)
        {
            BitMEXApi api    = new BitMEXApi(A.APIKey, A.SecretKey);
            string    result = api.GetOrders(this.comboBox_RecentTradesSymbol.Text);

            Console.WriteLine(result);
        }
Ejemplo n.º 10
0
        public ExecutionReport CancelOrder(Order order)
        {
            BitMEXApi       api          = new BitMEXApi(URL, ID, Secret);
            ExecutionReport beExecReport = null;

            var param = new Dictionary <string, string>();

            //param["clOrdIDs"] = order.ClOrdId;
            param["orderID"] = order.OrderId;
            //param["orderID"] = "132";

            string resp = api.Delete("/order", param, true);

            ExecutionReport[] reports = JsonConvert.DeserializeObject <ExecutionReport[]>(resp);

            if (reports.Length > 0)
            {
                beExecReport = MapExecutionReport(reports[0]);
            }
            else
            {
                throw new Exception(string.Format("No execution report received on order cancelation:{0}", order.OrderId));
            }

            return(beExecReport);
        }
Ejemplo n.º 11
0
        public double GetOrderBook(Account A, string CurrencyType)
        {
            double AveragePrice = 0.0f;
            int    count        = 0;

            try
            {
                BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);

                string trades = bitmex.QueryNonv1("GET", URL, null, false, false);
                trades = JsonHelper.FormatJson(trades);
                //trades = trades.Remove(0, 1);
                trades = trades.Remove(trades.IndexOf("\"asks\":"));
                trades = trades + "}";
                Console.WriteLine(trades);
                //string friendlyString = OrderBook.Remove(OrderBook.IndexOf("\"bids\":"), 7);
                //friendlyString = friendlyString.Remove(0, 1);

                bids = JsonConvert.DeserializeObject <List <Dictionary <double, int> > >(trades);
                //Console.WriteLine(bids[0]);
            }
            catch
            {
                Console.WriteLine("End of book or error. If shown orders, no error");
                return(AveragePrice / count);
            }

            return(AveragePrice / count);
        }
Ejemplo n.º 12
0
        public BitmexDataService(TradinServer tradingServer, DataBase data_base)
        {
            if (tradingServer == TradinServer.Real)
            {
                WebSocket = new WebSocketWrapper("wss://www.bitmex.com/realtime");
                Api       = new BitMEXApi(Settings.bitmexApiKey, Settings.bitmexApiSecret, true);           // false - demo, true - real account
            }
            else
            {
                WebSocket = new WebSocketWrapper("wss://testnet.bitmex.com/realtime");
                Api       = new BitMEXApi(Settings.bitmexDemoApiKey, Settings.bitmexDemoApiSecret, false);
            }

            dataBase = data_base;             // Data base methods are gonna be called in TradeBitmex etc.

            Instruments      = Api.GetActiveInstruments().OrderByDescending(a => a.Volume24H).ToList().AsReadOnly();
            ActiveInstrument = Instruments[0];

            WebSocket.Connect();

            // Authenticate websocket API
            var apiExpires = Api.GetExpiresArg();

            if (tradingServer == TradinServer.Real)
            {
                var signature = Api.GetWebSocketSignatureString(Settings.bitmexApiSecret, apiExpires);
                WebSocket.Send($@"{{""op"": ""authKeyExpires"", ""args"": [""{Settings.bitmexApiKey}"", {apiExpires}, ""{signature}""]}}");
            }
            else
            {
                var signature = Api.GetWebSocketSignatureString(Settings.bitmexDemoApiSecret, apiExpires);
                WebSocket.Send($@"{{""op"": ""authKeyExpires"", ""args"": [""{Settings.bitmexDemoApiKey}"", {apiExpires}, ""{signature}""]}}");
            }
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> position([FromQuery] string name)
        {
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    return(BadRequest("missing params"));
                }

                Document doc = new Document();
                string   positionjson;

                try
                {
                    AmazonDynamoDBClient amazonDynamoDB = new AmazonDynamoDBClient();
                    Table table = Table.LoadTable(amazonDynamoDB, "CartelBotRegistry");

                    doc = await table.GetItemAsync(name);
                }
                catch
                {
                    return(BadRequest("error finding name"));
                }

                BitmexPositionModel model  = new BitmexPositionModel();
                BitMEXApi           bitmex = new BitMEXApi(doc["Key"], doc["Secret"]);

                try
                {
                    positionjson = await bitmex.getPosition();
                }
                catch
                {
                    return(BadRequest("error connecting to bitmex"));
                }

                try
                {
                    model = JsonConvert.DeserializeObject <BitmexPositionModel>(positionjson);
                }
                catch
                {
                    return(BadRequest("error parsing data"));
                }

                PositionResponse response = new PositionResponse();
                response.name     = name;
                response.position = model.Position[0].currentQty;
                response.entry    = model.Position[0].avgEntryPrice;

                string responsejson = JsonConvert.SerializeObject(response);

                return(Content(responsejson, "application/json"));
            }
            catch
            {
                return(BadRequest("something went wrong"));
            }
        }
Ejemplo n.º 14
0
        private void Run(string[] args)
        {
            BitMEXApi bitmex = new BitMEXApi(bitmexKey, bitmexSecret);
            // var orderBook = bitmex.GetOrderBook("XBTUSD", 3);
            var orders = bitmex.GetOrders();

            Console.WriteLine(orders);
        }
Ejemplo n.º 15
0
        public string GetWallet(string symbol)
        {
            BitMEXApi bitmex = new BitMEXApi(this.APIKey, this.SecretKey);
            var       param  = new Dictionary <string, string>();

            param["symbol"] = symbol;
            return(bitmex.Query("GET", "/user/wallet", param, true));
        }
Ejemplo n.º 16
0
        public ActionResult Index()
        {
            BitMEXApi bitmex = new BitMEXApi(bitmexKey, bitmexSecret);
            var       orders = bitmex.PostOrders();
            var       temp   = orders.IndexOf("price");

            ViewBag.Value = orders.Substring(temp + 7, 4);
            return(View());
        }
Ejemplo n.º 17
0
 private void btnCancelOpenOrders_Click(object sender, EventArgs e)
 {
     foreach (ApiKey apiKey in apiKeyList)
     {
         bitmex = new BitMEXApi(apiKey);
         Wallet wallet = new Wallet();
         bitmex.CancelAllOpenOrders(ActiveInstrument.Symbol);
     }
 }
Ejemplo n.º 18
0
        public ExecutionReport PlaceOrder(Order order)
        {
            order.ValidateOrder();
            //We use the class that was provided by BitMex @https://github.com/BitMEX/api-connectors
            //Propper version for C++
            BitMEXApi api = new BitMEXApi(URL, ID, Secret);

            var param = new Dictionary <string, string>();

            param["clOrdId"]  = order.ClOrdId;
            param["symbol"]   = order.SymbolPair;
            param["side"]     = order.GetSide();
            param["orderQty"] = order.OrderQty.HasValue ? order.OrderQty.Value.ToString("0.########") : "0";
            param["ordType"]  = order.GetOrdType();

            if (order.TimeInForce.HasValue)
            {
                param["timeInForce"] = order.TimeInForce.Value.ToString();
            }

            if (order.Price.HasValue)
            {
                param["price"] = order.Price.Value.ToString("0.########");
            }

            if (order.StopPx.HasValue)
            {
                param["stopPx"] = order.StopPx.Value.ToString("0.########");
            }

            if (order.TriggeringPrice.HasValue)//In BitMex we assign the triggering price using the "stopPx" field
            {
                param["stopPx"] = order.TriggeringPrice.Value.ToString("0.########");
            }

            param["execInst"] = order.ExecInst;

            string resp = api.Query("POST", "/order", param, true);

            if (resp.Contains("error"))
            {
                throw new Exception(resp);
            }

            ExecutionReport report = JsonConvert.DeserializeObject <ExecutionReport>(resp);

            ExecutionReport beExecReport = MapExecutionReport(report);

            order.OrderId      = beExecReport.OrderID;
            beExecReport.Order = order;

            return(beExecReport);
        }
Ejemplo n.º 19
0
        public double GetWalletBalance()
        {
            double    Satoshi = 0.0f;
            BitMEXApi bitmex  = new BitMEXApi(this.APIKey, this.SecretKey);
            string    Result  = bitmex.Query("GET", WalletBalanceURL, null, true, false);

            Console.WriteLine(Result);
            var data = JsonConvert.DeserializeObject <Account>(Result);

            Satoshi   = data.walletBalance;
            AccountId = data.account;
            return(Satoshi);
        }
Ejemplo n.º 20
0
        public bool PostMessage(Account A, string msg)
        {
            BitMEXApi Api = new BitMEXApi(A.APIKey, A.SecretKey);

            Dictionary <string, string> Params = new Dictionary <string, string>();

            Params.Add("channelID", "1");
            Params.Add("message", msg);
            string Result = Api.Query("POST", "/chat", Params, true, false);

            Console.WriteLine(Result);

            return(true);
        }
Ejemplo n.º 21
0
 private void btnBuy_Click(object sender, EventArgs e)
 {
     foreach (ApiKey apiKey in apiKeyList)
     {
         bitmex = new BitMEXApi(apiKey);
         Wallet wallet   = bitmex.GetWallet();
         var    price    = Convert.ToDouble(inputPrice.Value);
         var    quantity = getQuantity(wallet, Convert.ToInt32(inputQuantity.Value), price, Convert.ToInt32(inputLeverage.Value));
         if (quantity > 0)
         {
             //MakeOrder("Buy", quantity, price);
         }
     }
 }
Ejemplo n.º 22
0
        public List <OrderBookEntry> GetOrderBook(string symbol)
        {
            BitMEXApi             api    = new BitMEXApi(URL);
            List <OrderBookEntry> orders = new List <OrderBookEntry>();

            var param = new Dictionary <string, string>();

            param.Add("symbol", symbol);
            string resp = api.Query("GET", _ORDER_BOOK_L2, param, false);

            List <OrderBookEntry> orderBookEntryList = JsonConvert.DeserializeObject <List <OrderBookEntry> >(resp);

            return(orderBookEntryList);
        }
Ejemplo n.º 23
0
        private void InitializeAPI()
        {
            try
            {
                bitmex = new BitMEXApi(APIKey, APISecret, RealNetwork);
                UpdateBalance();

                // Start our HeartBeat
                Heartbeat.Start();
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 24
0
        private void Run(string[] args)
        {
            BitMEXApi bitmex = new BitMEXApi(bitmexKey, bitmexSecret);
            // var orderBook = bitmex.GetOrderBook("XBTUSD", 3);
            //var orders = bitmex.GetOrders();

            var leverage = bitmex.Leverage("XBTUSD", 100);

            //bitmex.PostOrders();

            // var orders = bitmex.DeleteOrders();
            //Console.WriteLine(orders);

            Console.ReadKey();
        }
Ejemplo n.º 25
0
        //public Quote GetQuote(string symbol)
        //{
        //    BitMEXApi api = new BitMEXApi(URL);
        //    var param = new Dictionary<string, string>();
        //    param.Add("symbol", symbol);
        //    string resp = api.Query("GET", _QUOTE, param, false);

        //    Quote quote = JsonConvert.DeserializeObject<Quote>(resp);

        //    return quote;
        //}

        public List <Trade> GetTrades(string symbol, int count)
        {
            BitMEXApi    api    = new BitMEXApi(URL);
            List <Trade> trades = new List <Trade>();

            var param = new Dictionary <string, string>();

            param.Add("symbol", symbol);
            param.Add("count", count.ToString());
            param.Add("reverse", true.ToString());
            string resp = api.Query("GET", _TRADES, param, false);

            List <Trade> tradeList = JsonConvert.DeserializeObject <List <Trade> >(resp);

            return(tradeList);
        }
Ejemplo n.º 26
0
        private void InitializeAPI()
        {
            switch (ddlNetwork.SelectedItem.ToString())
            {
            case "TestNet":
                bitmex = new BitMEXApi(apiKeyList[0]);
                break;

            case "RealNet":
                bitmex = new BitMEXApi(apiKeyList[0]);
                break;
            }

            // We must do this in case symbols are different on test and real net
            InitializeSymbolInformation();
        }
Ejemplo n.º 27
0
        public void GetLeverage(Account A, string Symbol)
        {
            BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);

            try
            {
                string Lev = bitmex.Query("GET", URL, null, true, true);
                Console.WriteLine(Lev);

                string jsonshit = JsonConvert.DeserializeObject <string>(Lev);
                Console.WriteLine(jsonshit);
            }
            catch
            {
                Console.WriteLine("Couldn't fetch leverage");
            }
        }
Ejemplo n.º 28
0
        private void InitializeAPI()
        {
            switch (ddlNetwork.SelectedItem.ToString())
            {
            case "TestNet":
                bitmex = new BitMEXApi(textBoxKey.Text, textBoxSecret.Text, TestbitmexDomain);
                break;

            case "RealNet":
                bitmex = new BitMEXApi(textBoxKey.Text, textBoxSecret.Text, bitmexDomain);
                break;
            }

            // We must do this in case symbols are different on test and real net
            GetAPIValidity();
            InitializeSymbolInformation();
        }
Ejemplo n.º 29
0
        //public void CancellAll()
        //{
        //    BitMEXApi api = new BitMEXApi(URL, ID, Secret);

        //    var param = new Dictionary<string, string>();

        //    param["offset"] = "1" ;

        //    string resp = api.Query("POST", "/order/cancelAllAfter", param, true);
        //}

        public ExecutionReport[] GetOrders(string symbol = null)
        {
            BitMEXApi api = new BitMEXApi(URL, ID, Secret);

            var param = new Dictionary <string, string>();

            if (symbol != null)
            {
                param.Add("symbol", symbol);
            }
            param.Add("reverse", "true");
            //param.Add("count", 20.ToString());
            string resp = api.Query("GET", "/order", param, true);

            ExecutionReport[] reports = JsonConvert.DeserializeObject <ExecutionReport[]>(resp);

            return(reports);
        }
Ejemplo n.º 30
0
        public ExecutionReport[] CancelAll()
        {
            BitMEXApi api = new BitMEXApi(URL, ID, Secret);
            List <ExecutionReport> beExecReports = new List <ExecutionReport>();

            var param = new Dictionary <string, string>();

            string resp = api.Delete("/order/all", param, true);

            ExecutionReport[] reports = JsonConvert.DeserializeObject <ExecutionReport[]>(resp);

            foreach (ExecutionReport report in reports)
            {
                beExecReports.Add(MapExecutionReport(report));
            }

            return(beExecReports.ToArray());
        }