Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions QuantConnect.BybitBrokerage.Tests/BybitBrokerageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using QuantConnect.Brokerages.Bybit.Api;
using QuantConnect.Brokerages.Bybit.Models.Enums;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Logging;
Expand Down Expand Up @@ -62,8 +63,16 @@ protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISec
var websocketUrl = Config.Get("bybit-websocket-url", "wss://stream-testnet.bybit.com");

_client = CreateRestApiClient(apiKey, apiSecret, apiUrl);
return new BybitBrokerage(apiKey, apiSecret, apiUrl, websocketUrl, algorithm.Object, orderProvider,
securityProvider, new AggregationManager(), null);

return CreateBrokerage(apiKey, apiSecret, apiUrl, websocketUrl, algorithm.Object, orderProvider, securityProvider, new AggregationManager());
}

protected virtual IBrokerage CreateBrokerage(string apiKey, string apiSecret, string apiUrl,
string websocketUrl, IAlgorithm algorithm, IOrderProvider orderProvider, ISecurityProvider securityProvider,
IDataAggregator aggregator)
{
return new BybitBrokerage(apiKey, apiSecret, apiUrl, websocketUrl, algorithm, orderProvider, securityProvider, new AggregationManager(), null);

}

protected virtual decimal TakerFee => BybitFeeModel.TakerNonVIPFee;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using NUnit.Framework;

namespace QuantConnect.Brokerages.Bybit.Tests
{
[TestFixture, Explicit("Requires valid credentials to be setup and run outside USA")]
public class BybitInverseFuturesBrokerageHistoryProviderTests : BybitBrokerageHistoryProviderTests
{
private static readonly Symbol ETHUSD = Symbol.Create("ETHUSD", SecurityType.CryptoFuture, Market.Bybit);

private static TestCaseData[] ValidHistory
{
get
{
return new[]
{
// valid
new TestCaseData(ETHUSD, Resolution.Tick, Time.OneMinute, TickType.Trade),
new TestCaseData(ETHUSD, Resolution.Minute, Time.OneHour, TickType.Trade),
new TestCaseData(ETHUSD, Resolution.Hour, Time.OneDay, TickType.Trade),
new TestCaseData(ETHUSD, Resolution.Daily, TimeSpan.FromDays(15), TickType.Trade),
new TestCaseData(ETHUSD, Resolution.Hour, Time.OneDay, TickType.OpenInterest)
};
}
}

[Test, TestCaseSource(nameof(ValidHistory))]
public override void GetsHistory(Symbol symbol, Resolution resolution, TimeSpan period, TickType tickType)
{
base.GetsHistory(symbol, resolution, period, tickType);
}

[Ignore("The brokerage is shared between different product categories, therefore this test is only required in the base class")]
[TestCase(default, default, default, default)]
public override void ReturnsNullOnInvalidHistoryRequest(
Symbol symbol, Resolution resolution, TimeSpan period, TickType tickType)
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using NUnit.Framework;

namespace QuantConnect.Brokerages.Bybit.Tests
{
[TestFixture]
public partial class BybitInverseFuturesBrokerageTests
{
private static TestCaseData[] TestParameters
{
get
{
return new[]
{
// valid parameters, for example
new TestCaseData(BTCUSD, Resolution.Tick, false),
new TestCaseData(BTCUSD, Resolution.Minute, true),
new TestCaseData(BTCUSD, Resolution.Second, true),
};
}
}

[Test, TestCaseSource(nameof(TestParameters))]
public override void StreamsData(Symbol symbol, Resolution resolution, bool throwsException)
{
base.StreamsData(symbol, resolution, throwsException);
}
}
}
138 changes: 138 additions & 0 deletions QuantConnect.BybitBrokerage.Tests/BybitInverseFuturesBrokerageTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using QuantConnect.Brokerages.Bybit.Models.Enums;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Tests.Brokerages;
using QuantConnect.Util;

namespace QuantConnect.Brokerages.Bybit.Tests;

[TestFixture, Explicit("Requires valid credentials to be setup and run outside USA")]
public partial class BybitInverseFuturesBrokerageTests : BybitBrokerageTests
{
private static Symbol BTCUSD = Symbol.Create("BTCUSD", SecurityType.CryptoFuture, "bybit");
protected override Symbol Symbol { get; } = BTCUSD;

protected override SecurityType SecurityType => SecurityType.Future;
protected override BybitProductCategory Category => BybitProductCategory.Inverse;
protected override decimal TakerFee => 0.0000015m;

protected override decimal GetDefaultQuantity() => 10m;

protected override IBrokerage CreateBrokerage(string apiKey, string apiSecret, string apiUrl,
string websocketUrl, IAlgorithm algorithm, IOrderProvider orderProvider, ISecurityProvider securityProvider,
IDataAggregator aggregator)
{
return new BybitBrokerage(apiKey, apiSecret, apiUrl, websocketUrl, algorithm, orderProvider, securityProvider, new AggregationManager(), null);

}

/// <summary>
/// Provides the data required to test each order type in various cases
/// </summary>
private static TestCaseData[] OrderParameters()
{
return new[]
{
new TestCaseData(new MarketOrderTestParameters(BTCUSD)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(BTCUSD, 50000m, 10000m)).SetName("LimitOrder"),
new TestCaseData(new StopMarketOrderTestParameters(BTCUSD, 50000m, 10000m)).SetName("StopMarketOrder"),
new TestCaseData(new StopLimitOrderTestParameters(BTCUSD, 50000m, 10000m)).SetName("StopLimitOrder"),
new TestCaseData(new LimitIfTouchedOrderTestParameters(BTCUSD, 50000m, 20000)).SetName(
"LimitIfTouchedOrder")
};
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void CancelOrders(OrderTestParameters parameters)
{
base.CancelOrders(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void LongFromZero(OrderTestParameters parameters)
{
base.LongFromZero(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void CloseFromLong(OrderTestParameters parameters)
{
base.CloseFromLong(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void ShortFromZero(OrderTestParameters parameters)
{
base.ShortFromZero(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void CloseFromShort(OrderTestParameters parameters)
{
base.CloseFromShort(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void ShortFromLong(OrderTestParameters parameters)
{
base.ShortFromLong(parameters);
}

[Test, TestCaseSource(nameof(OrderParameters))]
public override void LongFromShort(OrderTestParameters parameters)
{
base.LongFromShort(parameters);
}


[Test]
public override void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetCashBalance();

var order = new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.UtcNow);
PlaceOrderWaitForStatus(order);

Thread.Sleep(3000);

var after = Brokerage.GetCashBalance();

CurrencyPairUtil.DecomposeCurrencyPair(Symbol, out var baseCurrency, out _);
var beforeHoldings = before.FirstOrDefault(x => x.Currency == baseCurrency);
var afterHoldings = after.FirstOrDefault(x => x.Currency == baseCurrency);

var beforeQuantity = beforeHoldings == null ? 0 : beforeHoldings.Amount;
var afterQuantity = afterHoldings == null ? 0 : afterHoldings.Amount;

var fee = 0.00000015m;

Assert.AreEqual(0, afterQuantity - beforeQuantity + fee);
}

}
1 change: 0 additions & 1 deletion QuantConnect.BybitBrokerage/Api/BybitAccountApiEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public BybitAccountApiEndpoint(ISymbolMapper symbolMapper, string apiPrefix, ISe
/// <summary>
/// Obtain wallet balance, query asset information of each currency, and account risk rate information
/// </summary>
/// <param name="category">The product category</param>
/// <returns>The wallet balances</returns>
public BybitBalance GetWalletBalances()
{
Expand Down
9 changes: 6 additions & 3 deletions QuantConnect.BybitBrokerage/Api/BybitPositionApiEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,13 @@ public IEnumerable<BybitPositionInfo> GetPositions(BybitProductCategory category
{
if (category == BybitProductCategory.Spot) return Array.Empty<BybitPositionInfo>();

var parameters = new KeyValuePair<string, string>[]
var parameters = new List<KeyValuePair<string, string>>();

if (category == BybitProductCategory.Linear)
{
new("settleCoin", "USDT")
};
parameters.Add(KeyValuePair.Create("settleCoin", "USDT"));
}

return FetchAll<BybitPositionInfo>("/position/list", category, 200, parameters, true);
}
}
14 changes: 9 additions & 5 deletions QuantConnect.BybitBrokerage/BybitBrokerage.Brokerage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public partial class BybitBrokerage
public override List<Order> GetOpenOrders()
{
var orders = new List<Order>();
foreach (var category in SupportedBybitProductCategories)
foreach (var category in GetWorkingProductCategories(_algorithm.BrokerageName))
{
orders.AddRange(ApiClient.Trade.GetOpenOrders(category)
.Select(bybitOrder =>
Expand Down Expand Up @@ -98,7 +98,7 @@ public override List<Order> GetOpenOrders()
public override List<Holding> GetAccountHoldings()
{
var holdings = new List<Holding>();
foreach (var category in SupportedBybitProductCategories)
foreach (var category in GetWorkingProductCategories(_algorithm.BrokerageName))
{
holdings.AddRange(ApiClient.Position.GetPositions(category)
.Select(bybitPosition => new Holding
Expand All @@ -121,9 +121,13 @@ public override List<Holding> GetAccountHoldings()
/// <returns>The current cash balance for each currency available for trading</returns>
public override List<CashAmount> GetCashBalance()
{
return ApiClient.Account
.GetWalletBalances().Assets
.Select(x => new CashAmount(x.WalletBalance, x.Asset)).ToList();
var balances = ApiClient.Account.GetWalletBalances();
if (GetWorkingProductCategories(_algorithm.BrokerageName).Contains(BybitProductCategory.Inverse))
{
return [new CashAmount(balances.TotalAvailableBalance ?? 0, "USD")];
}

return balances.Assets.Select(x => new CashAmount(x.WalletBalance, x.Asset)).ToList();
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions QuantConnect.BybitBrokerage/BybitBrokerage.Messaging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ private void HandleOrderExecution(JToken message)
var currency = tradeUpdate.Category switch
{
BybitProductCategory.Linear => "USDT",
BybitProductCategory.Inverse => GetBaseCurrency(symbol),
BybitProductCategory.Inverse => GetBaseCurrency(leanSymbol),
BybitProductCategory.Spot => GetSpotFeeCurrency(leanSymbol, tradeUpdate),
_ => throw new NotSupportedException($"category {tradeUpdate.Category} not implemented")
};
Expand Down Expand Up @@ -186,7 +186,7 @@ static string GetSpotFeeCurrency(Symbol symbol, BybitTradeUpdate tradeUpdate)
return tradeUpdate.Side == OrderSide.Buy ? quote : @base;
}

static string GetBaseCurrency(string pair)
static string GetBaseCurrency(Symbol pair)
{
CurrencyPairUtil.DecomposeCurrencyPair(pair, out var baseCurrency, out _);
return baseCurrency;
Expand Down
Loading