Ejemplo n.º 1
0
        public IEnumerable <BfaPrivateExecution> GetPrivateExecutions(BfProductCode productCode, long before, Func <BfaPrivateExecution, bool> predicate)
        {
            while (true)
            {
                var execs = GetPrivateExecutions(productCode, ReadCountMax, before, 0).GetContent();
                if (execs.Length == 0)
                {
                    break;
                }

                foreach (var exec in execs)
                {
                    if (!predicate(exec))
                    {
                        yield break;
                    }
                    yield return(exec);
                }

                if (execs.Length < ReadCountMax)
                {
                    break;
                }
                before = execs.Last().ExecutionId;
            }
        }
Ejemplo n.º 2
0
        public HistoricalOhlcSource(ICacheFactory cacheFactory, BfProductCode productCode, TimeSpan frameSpan, DateTime endFrom, TimeSpan span, string cacheFolderBasePath)
        {
            // Create database file if not exists automatically
            _cache = cacheFactory.GetOhlcCache(productCode, frameSpan);
            var requestedCount = Convert.ToInt32(span.TotalMinutes / frameSpan.TotalMinutes);

            endFrom = endFrom.Round(frameSpan);
            var startTo = endFrom - span + frameSpan;
            var end     = endFrom - span + frameSpan;

            _source = Observable.Create <IFxOhlcvv>(observer =>
            {
                var query = _cache.GetOhlcsBackward(endFrom, span);
                if (query.Count() == requestedCount)
                {
                    query.ForEach(ohlc => observer.OnNext(ohlc));
                }
                else
                {
                    // Cryptowatch accepts close-time based range
                    CryptowatchOhlcSource.Get(productCode, frameSpan, endFrom + frameSpan, startTo + frameSpan).OrderByDescending(e => e.Start).ForEach(ohlc =>
                    {
                        _cache.Add(new DbHistoricalOhlc(ohlc, frameSpan));
                        observer.OnNext(ohlc);
                    });
                    _cache.SaveChanges();
                }
                observer.OnCompleted();
                return(() => { });
            });

            // Cryptowatchの取得リミットに到達していた場合の対処
        }
Ejemplo n.º 3
0
 static void StackExecutions(BitFlyerClient client, ICacheFactory factory, BfProductCode productCode, int count)
 {
     using (var cache = factory.GetExecutionCache(productCode))
     {
         var recs = cache.GetManageTable();
         cache.CommitCount *= 100;
         var completed   = new ManualResetEvent(false);
         var recordCount = 0;
         var sw          = new Stopwatch();
         sw.Start();
         new HistoricalExecutionSource(client, productCode, recs[0].EndExecutionId + count, recs[0].EndExecutionId).Subscribe(exec =>
         {
             cache.Add(exec);
             if ((++recordCount % 10000) == 0)
             {
                 Console.WriteLine("{0} {1} Completed {2} Elapsed", exec.ExecutedTime.ToLocalTime(), recordCount, sw.Elapsed);
             }
         },
                                                                                                                              () =>
         {
             cache.SaveChanges();
             sw.Stop();
             completed.Set();
         });
         completed.WaitOne();
         cache.SaveChanges();
     }
 }
Ejemplo n.º 4
0
 public BitFlyerResponse <string> CancelAllChildOrders(BfProductCode productCode)
 {
     return(CancelAllChildOrders(new BfCancelAllChildOrdersRequest
     {
         ProductCode = productCode,
     }));
 }
Ejemplo n.º 5
0
 static void FillGaps(BitFlyerClient client, ICacheFactory factory, BfProductCode productCode)
 {
     using (var cache = factory.GetExecutionCache(productCode))
     {
         cache.CommitCount *= 100;
         var completed   = new ManualResetEvent(false);
         var recordCount = 0;
         var sw          = new Stopwatch();
         sw.Start();
         cache.FillGaps(client).Subscribe(exec =>
         {
             if ((++recordCount % 10000) == 0)
             {
                 Console.WriteLine("{0} {1} Completed {2} Elapsed", exec.ExecutedTime.ToLocalTime(), recordCount, sw.Elapsed);
             }
         },
                                          () =>
         {
             cache.SaveChanges();
             sw.Stop();
             completed.Set();
         });
         completed.WaitOne();
     }
 }
Ejemplo n.º 6
0
 public void StartExecutionSource(BfProductCode productCode)
 {
     if (_executionColdSources.TryGetValue(_availableMarkets[productCode], out IConnectableObservable <BfExecution> source))
     {
         source.Connect().AddTo(_disposables);
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// List Orders
        /// <see href="https://scrapbox.io/BitFlyerDotNet/GetChildOrders">Online help</see>
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="orderState"></param>
        /// <param name="count"></param>
        /// <param name="before"></param>
        /// <param name="after"></param>
        /// <param name="childOrderId"></param>
        /// <param name="childOrderAcceptanceId"></param>
        /// <param name="parentOrderId"></param>
        /// <returns></returns>
        public Task <BitFlyerResponse <BfaChildOrder[]> > GetChildOrdersAsync(
            BfProductCode productCode,
            BfOrderState orderState,
            int count,
            uint before,
            uint after,
            string childOrderId,
            string childOrderAcceptanceId,
            string parentOrderId,
            CancellationToken ct
            )
        {
            var query = string.Format("product_code={0}{1}{2}{3}{4}{5}{6}{7}",
                                      productCode.ToEnumString(),
                                      orderState != BfOrderState.Unknown ? "&child_order_state=" + orderState.ToEnumString() : "",
                                      (count > 0)  ? $"&count={count}"   : "",
                                      (before > 0) ? $"&before={before}" : "",
                                      (after > 0)  ? $"&after={after}"   : "",
                                      !string.IsNullOrEmpty(childOrderId) ? "&child_order_id=" + childOrderId : "",
                                      !string.IsNullOrEmpty(childOrderAcceptanceId) ? "&child_order_acceptance_id=" + childOrderAcceptanceId : "",
                                      !string.IsNullOrEmpty(parentOrderId) ? "&parent_order_id=" + parentOrderId : ""
                                      );

            return(GetPrivateAsync <BfaChildOrder[]>(nameof(GetChildOrders), query, ct));
        }
Ejemplo n.º 8
0
        public IEnumerable <BfaChildOrder> GetChildOrders(BfProductCode productCode, BfOrderState orderState, uint before, Func <BfaChildOrder, bool> predicate)
        {
            while (true)
            {
                var orders = GetChildOrders(productCode, orderState, ReadCountMax, before).GetContent();
                if (orders.Length == 0)
                {
                    break;
                }

                foreach (var order in orders)
                {
                    if (!predicate(order))
                    {
                        yield break;
                    }
                    yield return(order);
                }

                if (orders.Length < ReadCountMax)
                {
                    break;
                }
                before = orders.Last().PagingId;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Send a New Order
        /// <see href="https://scrapbox.io/BitFlyerDotNet/SendChildOrder">Online help</see>
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="orderType"></param>
        /// <param name="side"></param>
        /// <param name="price"></param>
        /// <param name="size"></param>
        /// <param name="minuteToExpire"></param>
        /// <param name="timeInForce"></param>
        /// <returns></returns>
        public Task <BitFlyerResponse <BfChildOrderResponse> > SendChildOrderAsync(
            BfProductCode productCode,
            BfOrderType orderType,
            BfTradeSide side,
            decimal price,
            decimal size,
            int minuteToExpire,
            BfTimeInForce timeInForce,
            CancellationToken ct
            )
        {
            var request = new BfChildOrderRequest
            {
                ProductCode    = productCode,
                ChildOrderType = orderType,
                Side           = side,
                Price          = price,
                Size           = size,
                MinuteToExpire = minuteToExpire,
                TimeInForce    = timeInForce,
            };

            Validate(ref request);
            return(SendChildOrderAsync(request, ct));
        }
Ejemplo n.º 10
0
 public IEnumerable <BfaChildOrder> GetChildOrders(BfProductCode productCode, DateTime after) =>
 GetChildOrders(productCode, BfOrderState.Active, 0, e => e.ChildOrderDate >= after)
 .Concat(GetChildOrders(productCode, BfOrderState.Completed, 0, e => e.ChildOrderDate >= after))
 .Concat(GetChildOrders(productCode, BfOrderState.Canceled, 0, e => e.ChildOrderDate >= after))
 .Concat(GetChildOrders(productCode, BfOrderState.Expired, 0, e => e.ChildOrderDate >= after))
 .Concat(GetChildOrders(productCode, BfOrderState.Rejected, 0, e => e.ChildOrderDate >= after))
 .OrderByDescending(e => e.PagingId);
Ejemplo n.º 11
0
 // Parent orders
 public void Insert(BfProductCode productCode, BfParentOrderRequest req, BfParentOrderResponse resp)
 {
     ParentOrders.Add(new DbParentOrder(productCode, req, resp));
     for (int childOrderIndex = 0; childOrderIndex < req.Parameters.Count; childOrderIndex++)
     {
         ChildOrders.Add(new DbChildOrder(req, resp, childOrderIndex));
     }
 }
Ejemplo n.º 12
0
 public BfxMarket(BfxAccount account, BfProductCode productCode, BfxConfiguration config)
 {
     _account        = account;
     ProductCode     = productCode;
     Config          = config ?? new BfxConfiguration();
     _serverTimeSpan = TimeSpan.Zero;
     _account.RealtimeSource.ConnectionResumed += ConnectionResumed;
 }
 public IObservable <IBfExecution> GetExecutionCachedSource(BfProductCode productCode, int before)
 {
     return(_sources.GetOrAdd(productCode, _ => { return new ConcurrentDictionary <int, ExecutionCachedSource>(); })
            .GetOrAdd(before, __ =>
     {
         return new ExecutionCachedSource(_client, _cacheFactory.GetExecutionCache(productCode), productCode, before);
     }));
 }
Ejemplo n.º 14
0
 public BfDbContextSqlServer(string connStr, BfProductCode productCode)
     : base(new DbContextOptionsBuilder <BfDbContextSqlServer>().Options)
 {
     ConnStr     = connStr;
     ProductCode = productCode;
     ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
     Database.SetCommandTimeout(CommandTimeout);
 }
Ejemplo n.º 15
0
        static IDisposable SubscribeTickerSource(RealtimeSourceFactory factory, BfProductCode productCode)
        {
            var source = factory.GetTickerSource(productCode);

            return(source.Subscribe(ticker =>
            {
                Console.WriteLine($"{ticker.Timestamp} P:{ticker.LastTradedPrice} A:{ticker.BestAsk} B:{ticker.BestBid}");
            }));
        }
Ejemplo n.º 16
0
        public void InsertIfNotExits(BfProductCode productCode, BfaPrivateExecution exec)
        {
            var rec = GetExecutions().Where(e => e.ExecutionId == exec.ExecutionId).FirstOrDefault();

            if (rec == default)
            {
                Executions.Add(new DbPrivateExecution(productCode, exec));
            }
        }
Ejemplo n.º 17
0
        public static void Classinitialize(TestContext context)
        {
            _productCode = Enum.Parse <BfProductCode>(context.Properties["ProductCode"].ToString());

            // ApiKey and ApiSecret are defined in PrivateTest.runsettings
            // Should copy that file to any other directory such as desktop and fill them.
            _key    = context.Properties["ApiKey"].ToString();
            _secret = context.Properties["ApiSecret"].ToString();
        }
Ejemplo n.º 18
0
        static IDisposable SubscribeExecutionSource(RealtimeSourceFactory factory, BfProductCode productCode)
        {
            var source = factory.GetExecutionSource(productCode);

            return(source.Subscribe(exec =>
            {
                Console.WriteLine($"{exec.ExecutedTime} P:{exec.Price} A:{exec.Side} B:{exec.Size}");
            }));
        }
Ejemplo n.º 19
0
 public static void Classinitialize(TestContext context)
 {
     _productCode        = Enum.Parse <BfProductCode>(context.Properties["ProductCode"].ToString());
     _key                = context.Properties["ApiKey"].ToString();
     _secret             = context.Properties["ApiSecret"].ToString();
     _client             = new BitFlyerClient(_key, _secret);
     _cacheDirectoryPath = context.Properties["CacheDirectoryPath"].ToString();
     _connStr            = "data source=" + Path.Combine(_cacheDirectoryPath, "TradingApiTests.db3");
     //_connStr = "data source=" + Path.Combine(_cacheDirectoryPath, "account.db3");
 }
Ejemplo n.º 20
0
        public BfaParentOrder GetParentOrder(BfProductCode productCode, BfaParentOrderDetail detail)
        {
            var result = GetParentOrders(productCode, count: 1, before: detail.PagingId + 1).GetContent();

            if (result.Length == 0)
            {
                throw new KeyNotFoundException();
            }
            return(result[0]);
        }
Ejemplo n.º 21
0
 // Message builders
 public static BfParentOrderRequestParameter Market(BfProductCode productCode, BfTradeSide side, decimal size)
 {
     return(new ()
     {
         ProductCode = productCode,
         ConditionType = BfOrderType.Market,
         Side = side,
         Size = size,
     });
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Execution History
        /// <see href="https://scrapbox.io/BitFlyerDotNet/GetExecutions">Online help</see>
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="count"></param>
        /// <param name="before"></param>
        /// <param name="after"></param>
        /// <returns></returns>
        public Task <BitFlyerResponse <BfaExecution[]> > GetExecutionsAsync(BfProductCode productCode, long count, long before, long after, CancellationToken ct)
        {
            var query = string.Format("product_code={0}{1}{2}{3}",
                                      productCode.ToEnumString(),
                                      (count > 0) ? $"&count={count}" : "",
                                      (before > 0) ? $"&before={before}" : "",
                                      (after > 0) ? $"&after={after}" : ""
                                      );

            return(GetAsync <BfaExecution[]>(nameof(GetExecutions), query, ct));
        }
Ejemplo n.º 23
0
        public DbParentOrder(BfProductCode productCode, BfaParentOrderDetail order)
        {
            ProductCode = productCode;

            PagingId     = order.PagingId;
            OrderId      = order.ParentOrderId;
            OrderType    = order.OrderMethod;
            ExpireDate   = order.ExpireDate;
            TimeInForce  = order.TimeInForce;
            AcceptanceId = order.ParentOrderAcceptanceId;
        }
Ejemplo n.º 24
0
 public DbParentOrder(BfProductCode productCode, BfParentOrderRequest req, BfParentOrderResponse resp)
 {
     ProductCode = productCode;
     OrderType   = req.OrderMethod;
     TimeInForce = req.TimeInForce;
     if (TimeInForce == BfTimeInForce.NotSpecified)
     {
         TimeInForce = BfTimeInForce.GTC;
     }
     AcceptanceId = resp.ParentOrderAcceptanceId;
 }
Ejemplo n.º 25
0
        public BitFlyerResponse <BfExecution[]> GetExecutions(BfProductCode productCode, int count = 0, int before = 0, int after = 0)
        {
            var query = string.Format("product_code={0}{1}{2}{3}",
                                      productCode.ToEnumString(),
                                      (count > 0) ? $"&count={count}" : "",
                                      (before > 0) ? $"&before={before}" : "",
                                      (after > 0) ? $"&after={after}" : ""
                                      );

            return(Get <BfExecution[]>(nameof(GetExecutions), query));
        }
Ejemplo n.º 26
0
        public DbChildOrder(BfProductCode productCode, BfaChildOrder order)
        {
            ProductCode = productCode;
            Side        = order.Side;
            OrderType   = order.ChildOrderType;
            OrderSize   = order.Size;

            ChildOrderIndex = -1;

            Update(order);
        }
Ejemplo n.º 27
0
 public BitFlyerResponse <BfaChildOrder[]> GetChildOrders(
     BfProductCode productCode,
     BfOrderState orderState = BfOrderState.Unknown,
     int count                     = 0,
     uint before                   = 0,
     uint after                    = 0,
     string childOrderId           = null,
     string childOrderAcceptanceId = null,
     string parentOrderId          = null
     )
 => GetChildOrdersAsync(productCode, orderState, count, before, after, childOrderId, childOrderAcceptanceId, parentOrderId, CancellationToken.None).Result;
Ejemplo n.º 28
0
        public BitFlyerResponse <BfParentOrder[]> GetParentOrders(BfProductCode productCode, BfOrderState orderState = BfOrderState.Unknown, int count = 0, int before = 0, int after = 0)
        {
            var query = string.Format("product_code={0}{1}{2}{3}",
                                      productCode.ToEnumString(),
                                      orderState != BfOrderState.Unknown ? "&parent_order_state=" + orderState.ToEnumString() : "",
                                      (count > 0)  ? $"&count={count}"   : "",
                                      (before > 0) ? $"&before={before}" : "",
                                      (after > 0)  ? $"&after={after}"   : ""
                                      );

            return(PrivateGet <BfParentOrder[]>(nameof(GetParentOrders), query));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// List Parent Orders
        /// <see href="https://scrapbox.io/BitFlyerDotNet/GetParentOrders">Online help</see>
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="orderState"></param>
        /// <param name="count"></param>
        /// <param name="before"></param>
        /// <param name="after"></param>
        /// <returns></returns>
        public Task <BitFlyerResponse <BfaParentOrder[]> > GetParentOrdersAsync(BfProductCode productCode, BfOrderState orderState, int count, uint before, uint after, CancellationToken ct)
        {
            var query = string.Format("product_code={0}{1}{2}{3}",
                                      productCode.ToEnumString(),
                                      orderState != BfOrderState.Unknown ? "&parent_order_state=" + orderState.ToEnumString() : "",
                                      (count > 0)  ? $"&count={count}"   : "",
                                      (before > 0) ? $"&before={before}" : "",
                                      (after > 0)  ? $"&after={after}"   : ""
                                      );

            return(GetPrivateAsync <BfaParentOrder[]>(nameof(GetParentOrders), query, ct));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Cancel parent order
        /// <see href="https://scrapbox.io/BitFlyerDotNet/CancelParentOrder">Online help</see>
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="parentOrderId"></param>
        /// <param name="parentOrderAcceptanceId"></param>
        /// <returns></returns>
        public async Task <BitFlyerResponse <string> > CancelParentOrderAsync(BfProductCode productCode, string parentOrderId, string parentOrderAcceptanceId, CancellationToken ct)
        {
            var request = new BfCancelParentOrderRequest
            {
                ProductCode             = productCode,
                ParentOrderId           = parentOrderId,
                ParentOrderAcceptanceId = parentOrderAcceptanceId
            };

            Validate(ref request);
            return(await PostPrivateAsync <string>(nameof(CancelParentOrder), request, ct));
        }