Lean  $LEAN_TAG$
ITokenBucket.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Threading;
18 
20 {
21  /// <summary>
22  /// Defines a token bucket for rate limiting
23  /// See: https://en.wikipedia.org/wiki/Token_bucket
24  /// </summary>
25  /// <remarks>
26  /// This code is ported from https://github.com/mxplusb/TokenBucket - since it's a dotnet core
27  /// project, there were issued importing the nuget package directly. The referenced repository
28  /// is provided under the Apache V2 license.
29  /// </remarks>
30  public interface ITokenBucket
31  {
32  /// <summary>
33  /// Gets the maximum capacity of tokens this bucket can hold.
34  /// </summary>
35  long Capacity { get; }
36 
37  /// <summary>
38  /// Gets the total number of currently available tokens for consumption
39  /// </summary>
40  long AvailableTokens { get; }
41 
42  /// <summary>
43  /// Blocks until the specified number of tokens are available for consumption
44  /// and then consumes that number of tokens.
45  /// </summary>
46  /// <param name="tokens">The number of tokens to consume</param>
47  /// <param name="timeout">The maximum amount of time, in milliseconds, to block. A <see cref="TimeoutException"/>
48  /// is throw in the event it takes longer than the stated timeout to consume the requested number of tokens.
49  /// The default timeout is set to infinite, which will block forever.</param>
50  void Consume(long tokens, long timeout = Timeout.Infinite);
51 
52  /// <summary>
53  /// Attempts to consume the specified number of tokens from the bucket. If the
54  /// requested number of tokens are not immediately available, then this method
55  /// will return false to indicate that zero tokens have been consumed.
56  /// </summary>
57  bool TryConsume(long tokens);
58  }
59 }