コード例 #1
0
        public bool Next()
        {
            try
            {
                CUtility.Log("mtgox...");
                var client  = new RestClient("http://data.mtgox.com/api/1/BTCUSD/ticker_fast");
                var request = new RestRequest
                {
                    Method = Method.GET
                };
                var response = client.Execute <JsonGetTickerFastMtGox>(request);
                //if (response == null) return false;
                var ask = [email protected];
                var bid = [email protected];
                var now = [email protected];
                this.Ask  = decimal.Parse(ask, CultureInfo.InvariantCulture);
                this.Bid  = decimal.Parse(bid, CultureInfo.InvariantCulture);
                this.Date = CUtility.UnixTimeStampToDateTime((double)now / 1000000).AddHours(1);
                //CUtility.UnixTime.ConvertToDateTime((uint) now/1000000).AddHours(1); //DateTime.Now;
                CUtility.Log(string.Format("{0} {1}", this.Date.ToString(CultureInfo.InvariantCulture), this.Bid));
            }
            catch (Exception ex)
            {
                //throw;
                CUtility.Log(ex.Message + " " + ex.StackTrace);
                return(true); // non puo' mai essere false se capita un errore su mtgox
            }

            return(true);
        }
コード例 #2
0
        protected bool InitCandles(CMarket market, CBitcoinCharts _candleSource)
        {
            //http://api.bitcoincharts.com/v1/trades.csv?symbol=mtgoxUSD

            /*
             * occorre un ciclo while che esamina bitcoincharts e cerca di estrarre i dati
             */

            CUtility.Log("reading candles");
            var candleWidth  = market.CandleMaker.CandleWidth;
            var candleLength = market.CandleMaker.QueueLength();

            var duration = candleWidth * candleLength;
            var from     = DateTime.Now.ToUniversalTime().AddSeconds(-duration);
            var to       = DateTime.Now.ToUniversalTime();
            var source   = _candleSource;
            var res      = source.GetTrades(from, to);

            CUtility.Log("creating candles");
            foreach (Trade trade in res)
            {
                try
                {
                    this.Buy    = trade.Price;
                    this.Date   = trade.Date;
                    this.Volume = trade.Amount;
                    OnTicker();

                    /*
                     * var date = trade.Date;
                     * var value = trade.Price;
                     * var amount = trade.Amount;
                     *
                     * // feed the candlemaker
                     * if (this.CandleMaker != null)
                     * {
                     * this.CandleMaker.CandleBuilder(date, value, amount);
                     * }
                     *
                     * if (this.CandleMakerHourly != null)
                     * {
                     * this.CandleMakerHourly.CandleBuilder(date, value, amount);
                     * }
                     */
                }
                catch (Exception ex)
                {
                    CUtility.Log(ex.Message);
                    //throw;
                }
            }
            CUtility.Log("start trading");
            //throw new NotImplementedException();
            return(true);
        }
コード例 #3
0
        protected void GetBalance()
        {
            try
            {
                //throw new NotImplementedException();
                CUtility.Log("");
                CUtility.Log(string.Format("[GetBalance] site:{0} ", this.Name));

                const string apiurl = "https://data.mtgox.com/api/2/";
                const string path   = "BTCUSD/money/info";

                var client  = new RestClient(apiurl + path);
                var request = new RestRequest();
                _nonce = getNonce(); //DateTime.Now.Ticks;
                //_nonce++;

                var data = "nonce=" + _nonce;

                var sign = getHash(Secret, path + Convert.ToChar(0) + data);
                request.AddHeader("Rest-Key", Apikey);
                request.AddHeader("Rest-Sign", sign);

                request.Method = Method.POST;
                request.AddParameter("nonce", _nonce);

                var response = client.Execute <JsonGetBalanceMtGox>(request);
                CUtility.Log(response.Content);

                var openorderBtc = decimal.Parse(response.Data.data.Wallets.BTC.Open_Orders.value,
                                                 CultureInfo.InvariantCulture.NumberFormat);
                var openorderMoney = decimal.Parse(response.Data.data.Wallets.USD.Open_Orders.value,
                                                   CultureInfo.InvariantCulture.NumberFormat);

                this.TotCoins =
                    decimal.Parse(response.Data.data.Wallets.BTC.Balance.value, CultureInfo.InvariantCulture.NumberFormat) -
                    openorderBtc;
                this.TotMoney =
                    decimal.Parse(response.Data.data.Wallets.USD.Balance.value, CultureInfo.InvariantCulture.NumberFormat) -
                    openorderMoney;

                this.HasOpenOrders = openorderBtc > 0 || openorderMoney > 0;

                this.Fee = decimal.Parse(response.Data.data.Trade_Fee, CultureInfo.InvariantCulture.NumberFormat) / 100;

                //OnGetBalance();
            }
            catch (Exception ex)
            {
                CUtility.Log(ex.Message);
                //this.SessionDisabled = true;
            }
        }
コード例 #4
0
        protected void OnTicker()
        {
            CUtility.Log(string.Format("{0} {1} SELL:{2} BUY:{3}", this.UniqueName, this.Date.ToString(CultureInfo.InvariantCulture), this.Sell, this.Buy));

            // feed the candlemaker
            var value = this.Buy;

            if (this.CandleMaker != null)
            {
                this.CandleMaker.CandleBuilder(this.Date, value, this.Volume);
            }

            if (this.CandleMakerHourly != null)
            {
                this.CandleMakerHourly.CandleBuilder(this.Date, value, this.Volume);
            }
        }
コード例 #5
0
        public override bool GetTicker()
        {
            if (!_simulatedDataSource.Next())
            {
                {
                    CUtility.Log("END OF SIMULATION : ");

                    this.Stop = true;
                    return(true);
                }
            }

            try
            {
                this.Sell = _simulatedDataSource.Ask;
                this.Buy  = _simulatedDataSource.Bid;

                if (MainConfiguration.Configuration.MarketSimulatorEnableNoise)
                {
                    var rnd   = new Random(1234);
                    var noise = (2 * rnd.NextDouble() - 1) * (double)MainConfiguration.Configuration.MarketSimulatorNoisePercent;
                    this.Buy *= (1 + (decimal)noise);
                    this.Sell = this.Buy * (1.05M);
                }

                if (this.CandleMaker != null)
                {
                    this.CandleMaker.CandleBuilder(_simulatedDataSource.Date, _simulatedDataSource.Bid, _simulatedDataSource.Volume);
                }

                if (this.CandleMakerHourly != null)
                {
                    this.CandleMakerHourly.CandleBuilder(_simulatedDataSource.Date, _simulatedDataSource.Bid, _simulatedDataSource.Volume);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
コード例 #6
0
        // }


        public bool Init(CMarket market)
        {
            //http://api.bitcoincharts.com/v1/trades.csv?symbol=mtgoxUSD

            /*
             * occorre un ciclo while che esamina bitcoincharts e cerca di estrarre i dati
             */

            CUtility.Log("reading candles");
            var candleWidth  = market.CandleMaker.CandleWidth;
            var candleLength = market.CandleMaker.QueueLength();

            var duration = candleWidth * candleLength;
            var from     = DateTime.Now.ToUniversalTime().AddSeconds(-duration);
            var to       = DateTime.Now.ToUniversalTime();
            var source   = new DataProvider.Sources.CBitcoinChartsMtgoxBtcusd();
            var res      = source.GetTrades(from, to);

            CUtility.Log("creating candles");
            foreach (Trade trade in res)
            {
                try
                {
                    var date   = trade.Date;
                    var value  = trade.Price;
                    var amount = trade.Amount;
                    market.CandleMaker.CandleBuilder(date, value, amount);
                    //CUtility.Log(string.Format("Candle {0} {1} ",date.ToString(CultureInfo.InvariantCulture),value.ToString(CultureInfo.InvariantCulture)));
                }
                catch (Exception ex)
                {
                    CUtility.Log(ex.Message);
                    //throw;
                }
            }
            CUtility.Log("start trading");
            //throw new NotImplementedException();
            return(true);
        }
コード例 #7
0
        public override bool DoCancelOrder(string orderId)
        {
            //if (PreDoCancelOrder(orderId))
            {
                const string apiurl = "https://data.mtgox.com/api/2/";
                const string path   = "BTCUSD/money/order/cancel";

                var client  = new RestClient(apiurl + path);
                var request = new RestRequest();
                _nonce = getNonce(); //DateTime.Now.Ticks;


                var data = "nonce=" + _nonce;

                //var amountInt = (Math.Round(amount, 8) * 100000000).ToString(CultureInfo.InvariantCulture);

                var parameters = new NameValueCollection
                {
                    { "oid", orderId }
                };

                /*
                 * if (price != null)
                 * {
                 *  var priceInt = (Math.Round((double)price, 5) * 100000).ToString(CultureInfo.InvariantCulture);
                 *  parameters.Add("price_int", priceInt);
                 * }
                 */
                var sign = getHash(Secret, path + Convert.ToChar(0) + data + ToQueryString(parameters));
                request.AddHeader("Rest-Key", Apikey);
                request.AddHeader("Rest-Sign", sign);

                request.Method = Method.POST;
                request.AddParameter("nonce", _nonce);
                foreach (string key in parameters.Keys)
                {
                    request.AddParameter(key, parameters[key]);
                }

                var response = client.Execute <JsonCancelOrderResponse>(request);
                CUtility.Log(response.Content);

                try
                {
                    var result = response.Data.Result == "success";

                    /*
                     * if (result != null)
                     * {
                     *  this.OnDoOrder(type, price, amount);
                     * }
                     * */
                    //if (result) OrdersInThisIteration--;
                    return(result);
                }
                catch (Exception e)
                {
                    CUtility.Log(e.Message);
                    return(false);
                }
            }
            return(false);
            //throw new NotImplementedException();
        }
コード例 #8
0
        public override string DoOrder(CUtility.OrderType type, decimal?price, decimal amount, ref string orderId, bool isMarket)
        {
            if (price == null)
            {
                return(null);
            }


            amount = Math.Round(amount, 8);
            price  = Math.Round(price.Value, this.Decimals);



            const string apiurl = "https://data.mtgox.com/api/2/";
            const string path   = "BTCUSD/money/order/add";

            var client  = new RestClient(apiurl + path);
            var request = new RestRequest();

            _nonce = getNonce(); // DateTime.Now.Ticks;


            var data = "nonce=" + _nonce;

            var amountInt = (Math.Round(amount, 8) * 100000000).ToString(CultureInfo.InvariantCulture);

            // Bid/ask
            string orderType = "bid";

            if (type == CUtility.OrderType.Sell)
            {
                orderType = "ask";
            }
            var parameters = new NameValueCollection
            {
                { "amount_int", amountInt },
                { "type", orderType }
            };

            //if (price != null)
            {
                if (!isMarket)
                {
                    var priceInt = (Math.Round((double)price, 5) * 100000).ToString(CultureInfo.InvariantCulture);
                    parameters.Add("price_int", priceInt);
                }
            }

            var sign = getHash(Secret, path + Convert.ToChar(0) + data + ToQueryString(parameters));

            request.AddHeader("Rest-Key", Apikey);
            request.AddHeader("Rest-Sign", sign);

            request.Method = Method.POST;
            request.AddParameter("nonce", _nonce);
            foreach (string key in parameters.Keys)
            {
                request.AddParameter(key, parameters[key]);
            }

            var response = client.Execute <JsonOrderResponse>(request);

            CUtility.Log(response.Content);

            try
            {
                var result = response.Data.Result == "success" ? response.Data.Data : null;
                if (result != null)
                {
                    orderId = response.Data.Data;
                    //this.OnDoOrder(type, price, amount, orderId,r2);
                    //OrdersInThisIteration++;
                }
                return(result);
            }
            catch (Exception e)
            {
                CUtility.Log(e.Message);
                return(null);
            }
        }
コード例 #9
0
        /*
         * public void GetOrders()
         * {
         *  //throw new NotImplementedException();
         *  CUtility.Log(string.Format("[GetOrders] site:{0} ", this.UniqueName));
         *
         *
         *  //http://data.mtgox.com/api/1/BTCUSD/depth/fetch (corretta)
         *
         *  const string url = "http://data.mtgox.com/api/1/BTCUSD/depth/fetch";
         *  CUtility.Log(url);
         *
         *  var client = new RestClient(url);
         *  var request = new RestRequest { Method = Method.GET };
         *
         *  //IRestResponse<JsonOrderBookMtGox>
         *  var response = client.Execute<JsonOrderBook>(request);
         *  //CApplication.Log(response.Content);
         *
         *  Asks.Clear();
         *  Bids.Clear();
         *
         *  // riempo gli ask e i bid
         *  if (response.Data != null && response.Data.Return != null)
         *  {
         *      foreach (var ll in response.Data.Return.asks)
         *      {
         *
         *          var ml = new CMarketListing
         *              {
         *                  Price = double.Parse(ll.Price, CultureInfo.InvariantCulture.NumberFormat),
         *                  BtcSize = double.Parse(ll.Amount, CultureInfo.InvariantCulture.NumberFormat),
         *                  Parent = this //,
         *                  //Date = CApplication.UnixTimeStampToDateTime(double.Parse(ll.Stamp.ToString(CultureInfo.InvariantCulture.NumberFormat), CultureInfo.InvariantCulture.NumberFormat))
         *              };
         *
         *          Asks.Add(ml);
         *
         *
         *      }
         *      foreach (var ll in response.Data.Return.bids)
         *      {
         *
         *          var ml = new CMarketListing
         *              {
         *                  Price = double.Parse(ll.Price, CultureInfo.InvariantCulture.NumberFormat),
         *                  BtcSize = double.Parse(ll.Amount, CultureInfo.InvariantCulture.NumberFormat),
         *                  Parent = this //,
         *                  //Date = CApplication.UnixTimeStampToDateTime(double.Parse(ll.Stamp.ToString(CultureInfo.InvariantCulture.NumberFormat), CultureInfo.InvariantCulture.NumberFormat))
         *              };
         *
         *          Bids.Add(ml);
         *
         *
         *      }
         *  }
         *  else
         *  {
         *      CUtility.Log(@"error");
         *  }
         *
         *  DoSaveTicker();
         * }
         */
        protected void GetOpenOrders()
        {
            try
            {
                //throw new NotImplementedException();
                CUtility.Log("");
                CUtility.Log(string.Format("[OpenOrders] site:{0} ", this.Name));

                const string apiurl = "https://data.mtgox.com/api/2/";
                const string path   = "BTCUSD/money/orders";

                var client  = new RestClient(apiurl + path);
                var request = new RestRequest();
                _nonce = getNonce(); //DateTime.Now.Ticks;
                //_nonce++;

                var data = "nonce=" + _nonce;

                var sign = getHash(Secret, path + Convert.ToChar(0) + data);
                request.AddHeader("Rest-Key", Apikey);
                request.AddHeader("Rest-Sign", sign);

                request.Method = Method.POST;
                request.AddParameter("nonce", _nonce);

                var response = client.Execute <JsonOrdersMtgox>(request);
                //CUtility.Log(response.Content);

                OpenOrders.RemoveAll(x => !response.Content.Contains(x.OrderId));

                var ordercompleted = true;
                foreach (var o in response.Data.Data)
                {
                    //if (o.oid == this.OrderIdR2)
                    {
                        //ordercompleted = false;
                    }
                }
                if (ordercompleted)
                {
                    //this.OrderIdR2 = string.Empty;
                }

                /*
                 * var openorderBtc = double.Parse(response.Data.data.Wallets.BTC.Open_Orders.value, CultureInfo.InvariantCulture.NumberFormat);
                 * var openorderMoney = double.Parse(response.Data.data.Wallets.USD.Open_Orders.value, CultureInfo.InvariantCulture.NumberFormat);
                 *
                 * this.AvailableBtc = double.Parse(response.Data.data.Wallets.BTC.Balance.value, CultureInfo.InvariantCulture.NumberFormat) - openorderBtc;
                 * this.AvailableMoney = double.Parse(response.Data.data.Wallets.USD.Balance.value, CultureInfo.InvariantCulture.NumberFormat) - openorderMoney;
                 *
                 * this.HasOpenOrder = openorderBtc > 0 || openorderMoney > 0;
                 */


                //this.Fee = double.Parse(response.Data.data.Trade_Fee, CultureInfo.InvariantCulture.NumberFormat) / 100;

                //OnGetBalance();
            }
            catch (Exception ex)
            {
                CUtility.Log(ex.Message);
                //this.SessionDisabled = true;
            }
        }