GMX v2 - Trading (#7)

* Move PrivateKeys.cs

* Update gitignore

* Update gitignore

* updt

* Extract GmxServiceTests.cs

* Refact

* update todo

* Update code

* Fix hashdata

* Replace static token hashed datas

* Set allowance

* Add get orders

* Add get orders tests

* Add ignore

* add close orders

* revert

* Add get gas limit

* Start increasePosition. Todo: Finish GetExecutionFee and estimateGas

* little refact

* Update gitignore

* Fix namespaces and clean repo

* Add tests samples

* Add execution fee

* Add increase position

* Handle backtest on the frontend

* Add tests

* Update increase

* Test increase

* fix increase

* Fix size

* Start get position

* Update get positions

* Fix get position

* Update rpc and trade mappers

* Finish close position

* Fix leverage
This commit is contained in:
Oda
2025-01-30 23:06:22 +07:00
committed by GitHub
parent ecaa89c67b
commit 65bdb8e34f
156 changed files with 11253 additions and 4073 deletions

20
.gitignore vendored
View File

@@ -347,22 +347,6 @@ obj
/Managing/Managing.Infrastructure.Storage/obj/Managing.Infrastructure.Storage.csproj.nuget.g.targets
/Managing/Managing.Infrastructure.Storage/obj/project.assets.json
/Managing/Managing.Infrastructure.Storage/obj/project.nuget.cache
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Application.dll
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Application.pdb
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Common.dll
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Common.pdb
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Core.dll
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Core.pdb
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Domain.dll
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Domain.pdb
/Managing/Managing.Infrastructure.Storage/obj/Debug/netstandard2.0/Managing.Infrastructure.Storage.assets.cache
/Managing/Managing.Infrastructure.Storage/obj/Debug/netstandard2.0/Managing.Infrastructure.Storage.csprojAssemblyReference.cache
/Managing/Managing.Infrastructure.Storage/obj/Managing.Infrastructure.Storage.csproj.nuget.dgspec.json
/Managing/Managing.Infrastructure.Storage/obj/Managing.Infrastructure.Storage.csproj.nuget.g.props
/Managing/Managing.Infrastructure.Storage/obj/Managing.Infrastructure.Storage.csproj.nuget.g.targets
/Managing/Managing.Infrastructure.Storage/obj/project.assets.json
/Managing/Managing.Infrastructure.Storage/obj/project.nuget.cache
/Managing/Managing.Infrastructure.Storage/bin/Debug/netstandard2.0/Managing.Application.dll
/Managing/src/Managing.Api/failures.txt
/Managing/src/Managing.Api.Workers/failures.txt
@@ -374,6 +358,8 @@ src/config.json
src/Managing.WebApp/src/pages/desk/desk.tsx
/src/Managing.Infrastructure.Tests/EvmBaseTests.cs
src/Managing.Api.Workers/appsettings.json
src/config.json
src/Managing.Api.Workers/appsettings.Oda-Sandbox.json
/src/Managing.WebApp/package-lock.json
src/Managing.Infrastructure.Tests/PrivateKeys.cs
/src/Managing.Infrastructure.Tests/PrivateKeys.cs
src/Managing.Infrastructure.Tests/PrivateKeys.cs

View File

@@ -96,7 +96,7 @@
- [x] Bot object should return MoneyManagement object
- [ ] Strategy can return a suggested trade that will give the best orders to execute
## Part 2 : Workflows builder
## Part 2 : Workflows builder (Post-pawned)
- [x] Create a workflow type that will encapsulate a list of flows
- [x] Each flow will have parameters, inputs and outputs that will be used by the children flows
@@ -134,8 +134,18 @@ ________________________________________________________________________________
# Phase 2 - Web3
- [x] Cancel Orders
- [x] Get open orders
- [x] Open trade (Increase position, decrease position)
- [x] Get position
- [x] Close trade
- [ ] Update position / TP / SL
## 0 - GMX v2
## 1 - Wallet management
- [ ] Create onboarding process for new wallet
- [ ] User can deposit token to and evm account with a QR code or clicking on button to copy the address
- [ ] Add account abstraction to level up security
@@ -177,7 +187,7 @@ ________________________________________________________________________________
- [ ] Remove link betweend Domain object to EVM project
- [ ] GMX Service should handle only Nethereum object, not Domain.Models
- [ ] Compute backtests pagination on backend side
- [ ] Store webapp into docker
- [x] Store webapp into docker
- [ ] Make possible to force close all positionpositions of a bot
- [ ] Save bot config to easily relaunch a bot and also analyze data
- [ ] Bot can handle limit order position -> fetch if order is still open then check if position of open

BIN
src/.DS_Store vendored Normal file

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,46 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateDepositParams : CreateDepositParamsBase
{
}
public class CreateDepositParamsBase
{
[Parameter("address", "receiver", 1)] public virtual string Receiver { get; set; }
[Parameter("address", "callbackContract", 2)]
public virtual string CallbackContract { get; set; }
[Parameter("address", "uiFeeReceiver", 3)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("address", "market", 4)] public virtual string Market { get; set; }
[Parameter("address", "initialLongToken", 5)]
public virtual string InitialLongToken { get; set; }
[Parameter("address", "initialShortToken", 6)]
public virtual string InitialShortToken { get; set; }
[Parameter("address[]", "longTokenSwapPath", 7)]
public virtual List<string> LongTokenSwapPath { get; set; }
[Parameter("address[]", "shortTokenSwapPath", 8)]
public virtual List<string> ShortTokenSwapPath { get; set; }
[Parameter("uint256", "minMarketTokens", 9)]
public virtual BigInteger MinMarketTokens { get; set; }
[Parameter("bool", "shouldUnwrapNativeToken", 10)]
public virtual bool ShouldUnwrapNativeToken { get; set; }
[Parameter("uint256", "executionFee", 11)]
public virtual BigInteger ExecutionFee { get; set; }
[Parameter("uint256", "callbackGasLimit", 12)]
public virtual BigInteger CallbackGasLimit { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateOrderParams : CreateOrderParamsBase
{
}
public class CreateOrderParamsBase
{
[Parameter("tuple", "addresses", 1)] public virtual CreateOrderParamsAddresses Addresses { get; set; }
[Parameter("tuple", "numbers", 2)] public virtual CreateOrderParamsNumbers Numbers { get; set; }
[Parameter("uint8", "orderType", 3)] public virtual byte OrderType { get; set; }
[Parameter("uint8", "decreasePositionSwapType", 4)]
public virtual byte DecreasePositionSwapType { get; set; }
[Parameter("bool", "isLong", 5)] public virtual bool IsLong { get; set; }
[Parameter("bool", "shouldUnwrapNativeToken", 6)]
public virtual bool ShouldUnwrapNativeToken { get; set; }
[Parameter("bool", "autoCancel", 7)] public virtual bool AutoCancel { get; set; }
[Parameter("bytes32", "referralCode", 8)]
public virtual byte[] ReferralCode { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateOrderParamsAddresses : CreateOrderParamsAddressesBase
{
}
public class CreateOrderParamsAddressesBase
{
[Parameter("address", "receiver", 1)] public virtual string Receiver { get; set; }
[Parameter("address", "cancellationReceiver", 2)]
public virtual string CancellationReceiver { get; set; }
[Parameter("address", "callbackContract", 3)]
public virtual string CallbackContract { get; set; }
[Parameter("address", "uiFeeReceiver", 4)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("address", "market", 5)] public virtual string Market { get; set; }
[Parameter("address", "initialCollateralToken", 6)]
public virtual string InitialCollateralToken { get; set; }
[Parameter("address[]", "swapPath", 7)]
public virtual List<string> SwapPath { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateOrderParamsNumbers : CreateOrderParamsNumbersBase
{
}
public class CreateOrderParamsNumbersBase
{
[Parameter("uint256", "sizeDeltaUsd", 1)]
public virtual BigInteger SizeDeltaUsd { get; set; }
[Parameter("uint256", "initialCollateralDeltaAmount", 2)]
public virtual BigInteger InitialCollateralDeltaAmount { get; set; }
[Parameter("uint256", "triggerPrice", 3)]
public virtual BigInteger TriggerPrice { get; set; }
[Parameter("uint256", "acceptablePrice", 4)]
public virtual BigInteger AcceptablePrice { get; set; }
[Parameter("uint256", "executionFee", 5)]
public virtual BigInteger ExecutionFee { get; set; }
[Parameter("uint256", "callbackGasLimit", 6)]
public virtual BigInteger CallbackGasLimit { get; set; }
[Parameter("uint256", "minOutputAmount", 7)]
public virtual BigInteger MinOutputAmount { get; set; }
[Parameter("uint256", "validFromTime", 8)]
public virtual BigInteger ValidFromTime { get; set; }
}
}

View File

@@ -0,0 +1,34 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateShiftParams : CreateShiftParamsBase
{
}
public class CreateShiftParamsBase
{
[Parameter("address", "receiver", 1)] public virtual string Receiver { get; set; }
[Parameter("address", "callbackContract", 2)]
public virtual string CallbackContract { get; set; }
[Parameter("address", "uiFeeReceiver", 3)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("address", "fromMarket", 4)]
public virtual string FromMarket { get; set; }
[Parameter("address", "toMarket", 5)] public virtual string ToMarket { get; set; }
[Parameter("uint256", "minMarketTokens", 6)]
public virtual BigInteger MinMarketTokens { get; set; }
[Parameter("uint256", "executionFee", 7)]
public virtual BigInteger ExecutionFee { get; set; }
[Parameter("uint256", "callbackGasLimit", 8)]
public virtual BigInteger CallbackGasLimit { get; set; }
}
}

View File

@@ -0,0 +1,43 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class CreateWithdrawalParams : CreateWithdrawalParamsBase
{
}
public class CreateWithdrawalParamsBase
{
[Parameter("address", "receiver", 1)] public virtual string Receiver { get; set; }
[Parameter("address", "callbackContract", 2)]
public virtual string CallbackContract { get; set; }
[Parameter("address", "uiFeeReceiver", 3)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("address", "market", 4)] public virtual string Market { get; set; }
[Parameter("address[]", "longTokenSwapPath", 5)]
public virtual List<string> LongTokenSwapPath { get; set; }
[Parameter("address[]", "shortTokenSwapPath", 6)]
public virtual List<string> ShortTokenSwapPath { get; set; }
[Parameter("uint256", "minLongTokenAmount", 7)]
public virtual BigInteger MinLongTokenAmount { get; set; }
[Parameter("uint256", "minShortTokenAmount", 8)]
public virtual BigInteger MinShortTokenAmount { get; set; }
[Parameter("bool", "shouldUnwrapNativeToken", 9)]
public virtual bool ShouldUnwrapNativeToken { get; set; }
[Parameter("uint256", "executionFee", 10)]
public virtual BigInteger ExecutionFee { get; set; }
[Parameter("uint256", "callbackGasLimit", 11)]
public virtual BigInteger CallbackGasLimit { get; set; }
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class Props : PropsBase
{
}
public class PropsBase
{
[Parameter("uint256", "min", 1)] public virtual BigInteger Min { get; set; }
[Parameter("uint256", "max", 2)] public virtual BigInteger Max { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class SetPricesParams : SetPricesParamsBase
{
}
public class SetPricesParamsBase
{
[Parameter("address[]", "tokens", 1)] public virtual List<string> Tokens { get; set; }
[Parameter("address[]", "providers", 2)]
public virtual List<string> Providers { get; set; }
[Parameter("bytes[]", "data", 3)] public virtual List<byte[]> Data { get; set; }
}
}

View File

@@ -0,0 +1,24 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.ExchangeRouter.ContractDefinition
{
public partial class SimulatePricesParams : SimulatePricesParamsBase
{
}
public class SimulatePricesParamsBase
{
[Parameter("address[]", "primaryTokens", 1)]
public virtual List<string> PrimaryTokens { get; set; }
[Parameter("tuple[]", "primaryPrices", 2)]
public virtual List<Props> PrimaryPrices { get; set; }
[Parameter("uint256", "minTimestamp", 3)]
public virtual BigInteger MinTimestamp { get; set; }
[Parameter("uint256", "maxTimestamp", 4)]
public virtual BigInteger MaxTimestamp { get; set; }
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -8,8 +8,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Nethereum.Contracts" Version="4.21.3"/>
<PackageReference Include="Nethereum.Web3" Version="4.21.2"/>
<PackageReference Include="Nethereum.Contracts" Version="4.28.0"/>
<PackageReference Include="Nethereum.Web3" Version="4.28.0"/>
</ItemGroup>
</Project>

View File

@@ -1,15 +0,0 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.Multicall3.ContractDefinition
{
public partial class Call3 : Call3Base
{
}
public class Call3Base
{
[Parameter("address", "target", 1)] public virtual string Target { get; set; }
[Parameter("bool", "allowFailure", 2)] public virtual bool AllowFailure { get; set; }
[Parameter("bytes", "callData", 3)] public virtual byte[] CallData { get; set; }
}
}

View File

@@ -1,17 +0,0 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.Multicall3.ContractDefinition
{
public partial class Call3Value : Call3ValueBase
{
}
public class Call3ValueBase
{
[Parameter("address", "target", 1)] public virtual string Target { get; set; }
[Parameter("bool", "allowFailure", 2)] public virtual bool AllowFailure { get; set; }
[Parameter("uint256", "value", 3)] public virtual BigInteger Value { get; set; }
[Parameter("bytes", "callData", 4)] public virtual byte[] CallData { get; set; }
}
}

File diff suppressed because one or more lines are too long

View File

@@ -7,20 +7,19 @@ namespace Managing.ABI.GmxV2.Multicall3
{
public partial class Multicall3Service : ContractWeb3ServiceBase
{
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.IWeb3 web3,
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(IWeb3 web3,
Multicall3Deployment multicall3Deployment, CancellationTokenSource cancellationTokenSource = null)
{
return web3.Eth.GetContractDeploymentHandler<Multicall3Deployment>()
.SendRequestAndWaitForReceiptAsync(multicall3Deployment, cancellationTokenSource);
}
public static Task<string> DeployContractAsync(Nethereum.Web3.IWeb3 web3,
Multicall3Deployment multicall3Deployment)
public static Task<string> DeployContractAsync(IWeb3 web3, Multicall3Deployment multicall3Deployment)
{
return web3.Eth.GetContractDeploymentHandler<Multicall3Deployment>().SendRequestAsync(multicall3Deployment);
}
public static async Task<Multicall3Service> DeployContractAndGetServiceAsync(Nethereum.Web3.IWeb3 web3,
public static async Task<Multicall3Service> DeployContractAndGetServiceAsync(IWeb3 web3,
Multicall3Deployment multicall3Deployment, CancellationTokenSource cancellationTokenSource = null)
{
var receipt =
@@ -28,7 +27,7 @@ namespace Managing.ABI.GmxV2.Multicall3
return new Multicall3Service(web3, receipt.ContractAddress);
}
public Multicall3Service(Nethereum.Web3.IWeb3 web3, string contractAddress) : base(web3, contractAddress)
public Multicall3Service(IWeb3 web3, string contractAddress) : base(web3, contractAddress)
{
}
@@ -60,62 +59,6 @@ namespace Managing.ABI.GmxV2.Multicall3
return ContractHandler.SendRequestAndWaitForReceiptAsync(aggregateFunction, cancellationToken);
}
public Task<string> Aggregate3RequestAsync(Aggregate3Function aggregate3Function)
{
return ContractHandler.SendRequestAsync(aggregate3Function);
}
public Task<TransactionReceipt> Aggregate3RequestAndWaitForReceiptAsync(Aggregate3Function aggregate3Function,
CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(aggregate3Function, cancellationToken);
}
public Task<string> Aggregate3RequestAsync(List<Call3> calls)
{
var aggregate3Function = new Aggregate3Function();
aggregate3Function.Calls = calls;
return ContractHandler.SendRequestAsync(aggregate3Function);
}
public Task<TransactionReceipt> Aggregate3RequestAndWaitForReceiptAsync(List<Call3> calls,
CancellationTokenSource cancellationToken = null)
{
var aggregate3Function = new Aggregate3Function();
aggregate3Function.Calls = calls;
return ContractHandler.SendRequestAndWaitForReceiptAsync(aggregate3Function, cancellationToken);
}
public Task<string> Aggregate3ValueRequestAsync(Aggregate3ValueFunction aggregate3ValueFunction)
{
return ContractHandler.SendRequestAsync(aggregate3ValueFunction);
}
public Task<TransactionReceipt> Aggregate3ValueRequestAndWaitForReceiptAsync(
Aggregate3ValueFunction aggregate3ValueFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(aggregate3ValueFunction, cancellationToken);
}
public Task<string> Aggregate3ValueRequestAsync(List<Call3Value> calls)
{
var aggregate3ValueFunction = new Aggregate3ValueFunction();
aggregate3ValueFunction.Calls = calls;
return ContractHandler.SendRequestAsync(aggregate3ValueFunction);
}
public Task<TransactionReceipt> Aggregate3ValueRequestAndWaitForReceiptAsync(List<Call3Value> calls,
CancellationTokenSource cancellationToken = null)
{
var aggregate3ValueFunction = new Aggregate3ValueFunction();
aggregate3ValueFunction.Calls = calls;
return ContractHandler.SendRequestAndWaitForReceiptAsync(aggregate3ValueFunction, cancellationToken);
}
public Task<string> BlockAndAggregateRequestAsync(BlockAndAggregateFunction blockAndAggregateFunction)
{
return ContractHandler.SendRequestAsync(blockAndAggregateFunction);
@@ -144,18 +87,6 @@ namespace Managing.ABI.GmxV2.Multicall3
return ContractHandler.SendRequestAndWaitForReceiptAsync(blockAndAggregateFunction, cancellationToken);
}
public Task<BigInteger> GetBasefeeQueryAsync(GetBasefeeFunction getBasefeeFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetBasefeeFunction, BigInteger>(getBasefeeFunction, blockParameter);
}
public Task<BigInteger> GetBasefeeQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetBasefeeFunction, BigInteger>(null, blockParameter);
}
public Task<byte[]> GetBlockHashQueryAsync(GetBlockHashFunction getBlockHashFunction,
BlockParameter blockParameter = null)
{
@@ -184,18 +115,6 @@ namespace Managing.ABI.GmxV2.Multicall3
return ContractHandler.QueryAsync<GetBlockNumberFunction, BigInteger>(null, blockParameter);
}
public Task<BigInteger> GetChainIdQueryAsync(GetChainIdFunction getChainIdFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetChainIdFunction, BigInteger>(getChainIdFunction, blockParameter);
}
public Task<BigInteger> GetChainIdQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetChainIdFunction, BigInteger>(null, blockParameter);
}
public Task<string> GetCurrentBlockCoinbaseQueryAsync(
GetCurrentBlockCoinbaseFunction getCurrentBlockCoinbaseFunction, BlockParameter blockParameter = null)
{
@@ -209,6 +128,19 @@ namespace Managing.ABI.GmxV2.Multicall3
return ContractHandler.QueryAsync<GetCurrentBlockCoinbaseFunction, string>(null, blockParameter);
}
public Task<BigInteger> GetCurrentBlockDifficultyQueryAsync(
GetCurrentBlockDifficultyFunction getCurrentBlockDifficultyFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetCurrentBlockDifficultyFunction, BigInteger>(
getCurrentBlockDifficultyFunction, blockParameter);
}
public Task<BigInteger> GetCurrentBlockDifficultyQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetCurrentBlockDifficultyFunction, BigInteger>(null, blockParameter);
}
public Task<BigInteger> GetCurrentBlockGasLimitQueryAsync(
GetCurrentBlockGasLimitFunction getCurrentBlockGasLimitFunction, BlockParameter blockParameter = null)
{
@@ -250,6 +182,19 @@ namespace Managing.ABI.GmxV2.Multicall3
return ContractHandler.QueryAsync<GetEthBalanceFunction, BigInteger>(getEthBalanceFunction, blockParameter);
}
public Task<BigInteger> GetL1BlockNumberQueryAsync(GetL1BlockNumberFunction getL1BlockNumberFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetL1BlockNumberFunction, BigInteger>(getL1BlockNumberFunction,
blockParameter);
}
public Task<BigInteger> GetL1BlockNumberQueryAsync(BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetL1BlockNumberFunction, BigInteger>(null, blockParameter);
}
public Task<byte[]> GetLastBlockHashQueryAsync(GetLastBlockHashFunction getLastBlockHashFunction,
BlockParameter blockParameter = null)
{
@@ -328,17 +273,15 @@ namespace Managing.ABI.GmxV2.Multicall3
return new List<Type>
{
typeof(AggregateFunction),
typeof(Aggregate3Function),
typeof(Aggregate3ValueFunction),
typeof(BlockAndAggregateFunction),
typeof(GetBasefeeFunction),
typeof(GetBlockHashFunction),
typeof(GetBlockNumberFunction),
typeof(GetChainIdFunction),
typeof(GetCurrentBlockCoinbaseFunction),
typeof(GetCurrentBlockDifficultyFunction),
typeof(GetCurrentBlockGasLimitFunction),
typeof(GetCurrentBlockTimestampFunction),
typeof(GetEthBalanceFunction),
typeof(GetL1BlockNumberFunction),
typeof(GetLastBlockHashFunction),
typeof(TryAggregateFunction),
typeof(TryBlockAndAggregateFunction)

View File

@@ -0,0 +1,26 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class Addresses : AddressesBase { }
public class AddressesBase
{
[Parameter("address", "account", 1)]
public virtual string Account { get; set; }
[Parameter("address", "receiver", 2)]
public virtual string Receiver { get; set; }
[Parameter("address", "cancellationReceiver", 3)]
public virtual string CancellationReceiver { get; set; }
[Parameter("address", "callbackContract", 4)]
public virtual string CallbackContract { get; set; }
[Parameter("address", "uiFeeReceiver", 5)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("address", "market", 6)]
public virtual string Market { get; set; }
[Parameter("address", "initialCollateralToken", 7)]
public virtual string InitialCollateralToken { get; set; }
[Parameter("address[]", "swapPath", 8)]
public virtual List<string> SwapPath { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class BaseFundingValues : BaseFundingValuesBase { }
public class BaseFundingValuesBase
{
[Parameter("tuple", "fundingFeeAmountPerSize", 1)]
public virtual PositionType FundingFeeAmountPerSize { get; set; }
[Parameter("tuple", "claimableFundingAmountPerSize", 2)]
public virtual PositionType ClaimableFundingAmountPerSize { get; set; }
}
}

View File

@@ -0,0 +1,15 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class CollateralType : CollateralTypeBase { }
public class CollateralTypeBase
{
[Parameter("uint256", "longToken", 1)]
public virtual BigInteger LongToken { get; set; }
[Parameter("uint256", "shortToken", 2)]
public virtual BigInteger ShortToken { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class ExecutionPriceResult : ExecutionPriceResultBase { }
public class ExecutionPriceResultBase
{
[Parameter("int256", "priceImpactUsd", 1)]
public virtual BigInteger PriceImpactUsd { get; set; }
[Parameter("uint256", "priceImpactDiffUsd", 2)]
public virtual BigInteger PriceImpactDiffUsd { get; set; }
[Parameter("uint256", "executionPrice", 3)]
public virtual BigInteger ExecutionPrice { get; set; }
}
}

View File

@@ -0,0 +1,18 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class Flags : FlagsBase
{
}
public class FlagsBase
{
// [Parameter("bool", "isLong", 1)] public virtual bool IsLong { get; set; }
// [Parameter("bool", "shouldUnwrapNativeToken", 2)]
// public virtual bool ShouldUnwrapNativeToken { get; set; }
// [Parameter("bool", "isFrozen", 3)]
// public virtual bool IsFrozen { get; set; }
[Parameter("bool", "autoCancel", 4)] public virtual bool AutoCancel { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class GetNextFundingAmountPerSizeResult : GetNextFundingAmountPerSizeResultBase { }
public class GetNextFundingAmountPerSizeResultBase
{
[Parameter("bool", "longsPayShorts", 1)]
public virtual bool LongsPayShorts { get; set; }
[Parameter("uint256", "fundingFactorPerSecond", 2)]
public virtual BigInteger FundingFactorPerSecond { get; set; }
[Parameter("int256", "nextSavedFundingFactorPerSecond", 3)]
public virtual BigInteger NextSavedFundingFactorPerSecond { get; set; }
[Parameter("tuple", "fundingFeeAmountPerSizeDelta", 4)]
public virtual PositionType FundingFeeAmountPerSizeDelta { get; set; }
[Parameter("tuple", "claimableFundingAmountPerSizeDelta", 5)]
public virtual PositionType ClaimableFundingAmountPerSizeDelta { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class IsPositionLiquidatableInfo : IsPositionLiquidatableInfoBase { }
public class IsPositionLiquidatableInfoBase
{
[Parameter("int256", "remainingCollateralUsd", 1)]
public virtual BigInteger RemainingCollateralUsd { get; set; }
[Parameter("int256", "minCollateralUsd", 2)]
public virtual BigInteger MinCollateralUsd { get; set; }
[Parameter("int256", "minCollateralUsdForLeverage", 3)]
public virtual BigInteger MinCollateralUsdForLeverage { get; set; }
}
}

View File

@@ -0,0 +1,31 @@
using System.Numerics;
using Managing.ABI.GmxV2.Reader.ContractDefinition;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class MarketInfo : MarketInfoBase
{
}
public class MarketInfoBase
{
[Parameter("tuple", "market", 1)] public virtual MarketsProps Market { get; set; }
[Parameter("uint256", "borrowingFactorPerSecondForLongs", 2)]
public virtual BigInteger BorrowingFactorPerSecondForLongs { get; set; }
[Parameter("uint256", "borrowingFactorPerSecondForShorts", 3)]
public virtual BigInteger BorrowingFactorPerSecondForShorts { get; set; }
[Parameter("tuple", "baseFunding", 4)] public virtual BaseFundingValues BaseFunding { get; set; }
[Parameter("tuple", "nextFunding", 5)]
public virtual GetNextFundingAmountPerSizeResult NextFunding { get; set; }
[Parameter("tuple", "virtualInventory", 6)]
public virtual VirtualInventory VirtualInventory { get; set; }
[Parameter("bool", "isDisabled", 7)] public virtual bool IsDisabled { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
using Managing.ABI.GmxV2.Reader.ContractDefinition;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class MarketPrices : MarketPricesBase
{
}
public class MarketPricesBase
{
[Parameter("tuple", "indexTokenPrice", 1)]
public virtual MarketPrice IndexTokenPrice { get; set; }
[Parameter("tuple", "longTokenPrice", 2)]
public virtual MarketPrice LongTokenPrice { get; set; }
[Parameter("tuple", "shortTokenPrice", 3)]
public virtual MarketPrice ShortTokenPrice { get; set; }
}
}

View File

@@ -0,0 +1,33 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class Numbers : NumbersBase { }
public class NumbersBase
{
[Parameter("uint8", "orderType", 1)]
public virtual byte OrderType { get; set; }
[Parameter("uint8", "decreasePositionSwapType", 2)]
public virtual byte DecreasePositionSwapType { get; set; }
[Parameter("uint256", "sizeDeltaUsd", 3)]
public virtual BigInteger SizeDeltaUsd { get; set; }
[Parameter("uint256", "initialCollateralDeltaAmount", 4)]
public virtual BigInteger InitialCollateralDeltaAmount { get; set; }
[Parameter("uint256", "triggerPrice", 5)]
public virtual BigInteger TriggerPrice { get; set; }
[Parameter("uint256", "acceptablePrice", 6)]
public virtual BigInteger AcceptablePrice { get; set; }
[Parameter("uint256", "executionFee", 7)]
public virtual BigInteger ExecutionFee { get; set; }
[Parameter("uint256", "callbackGasLimit", 8)]
public virtual BigInteger CallbackGasLimit { get; set; }
[Parameter("uint256", "minOutputAmount", 9)]
public virtual BigInteger MinOutputAmount { get; set; }
[Parameter("uint256", "updatedAtTime", 10)]
public virtual BigInteger UpdatedAtTime { get; set; }
[Parameter("uint256", "validFromTime", 11)]
public virtual BigInteger ValidFromTime { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionBorrowingFees : PositionBorrowingFeesBase { }
public class PositionBorrowingFeesBase
{
[Parameter("uint256", "borrowingFeeUsd", 1)]
public virtual BigInteger BorrowingFeeUsd { get; set; }
[Parameter("uint256", "borrowingFeeAmount", 2)]
public virtual BigInteger BorrowingFeeAmount { get; set; }
[Parameter("uint256", "borrowingFeeReceiverFactor", 3)]
public virtual BigInteger BorrowingFeeReceiverFactor { get; set; }
[Parameter("uint256", "borrowingFeeAmountForFeeReceiver", 4)]
public virtual BigInteger BorrowingFeeAmountForFeeReceiver { get; set; }
}
}

View File

@@ -0,0 +1,53 @@
using System.Numerics;
using Managing.ABI.GmxV2.Reader.ContractDefinition;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionFees : PositionFeesBase
{
}
public class PositionFeesBase
{
[Parameter("tuple", "referral", 1)] public virtual PositionReferralFees Referral { get; set; }
[Parameter("tuple", "pro", 2)] public virtual PositionProFees Pro { get; set; }
[Parameter("tuple", "funding", 3)] public virtual PositionFundingFees Funding { get; set; }
[Parameter("tuple", "borrowing", 4)] public virtual PositionBorrowingFees Borrowing { get; set; }
[Parameter("tuple", "ui", 5)] public virtual PositionUiFees Ui { get; set; }
[Parameter("tuple", "liquidation", 6)] public virtual PositionLiquidationFees Liquidation { get; set; }
[Parameter("tuple", "collateralTokenPrice", 7)]
public virtual MarketPrice CollateralTokenPrice { get; set; }
[Parameter("uint256", "positionFeeFactor", 8)]
public virtual BigInteger PositionFeeFactor { get; set; }
[Parameter("uint256", "protocolFeeAmount", 9)]
public virtual BigInteger ProtocolFeeAmount { get; set; }
[Parameter("uint256", "positionFeeReceiverFactor", 10)]
public virtual BigInteger PositionFeeReceiverFactor { get; set; }
[Parameter("uint256", "feeReceiverAmount", 11)]
public virtual BigInteger FeeReceiverAmount { get; set; }
[Parameter("uint256", "feeAmountForPool", 12)]
public virtual BigInteger FeeAmountForPool { get; set; }
[Parameter("uint256", "positionFeeAmountForPool", 13)]
public virtual BigInteger PositionFeeAmountForPool { get; set; }
[Parameter("uint256", "positionFeeAmount", 14)]
public virtual BigInteger PositionFeeAmount { get; set; }
[Parameter("uint256", "totalCostAmountExcludingFunding", 15)]
public virtual BigInteger TotalCostAmountExcludingFunding { get; set; }
[Parameter("uint256", "totalCostAmount", 16)]
public virtual BigInteger TotalCostAmount { get; set; }
[Parameter("uint256", "totalDiscountAmount", 17)]
public virtual BigInteger TotalDiscountAmount { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionFundingFees : PositionFundingFeesBase { }
public class PositionFundingFeesBase
{
[Parameter("uint256", "fundingFeeAmount", 1)]
public virtual BigInteger FundingFeeAmount { get; set; }
[Parameter("uint256", "claimableLongTokenAmount", 2)]
public virtual BigInteger ClaimableLongTokenAmount { get; set; }
[Parameter("uint256", "claimableShortTokenAmount", 3)]
public virtual BigInteger ClaimableShortTokenAmount { get; set; }
[Parameter("uint256", "latestFundingFeeAmountPerSize", 4)]
public virtual BigInteger LatestFundingFeeAmountPerSize { get; set; }
[Parameter("uint256", "latestLongTokenClaimableFundingAmountPerSize", 5)]
public virtual BigInteger LatestLongTokenClaimableFundingAmountPerSize { get; set; }
[Parameter("uint256", "latestShortTokenClaimableFundingAmountPerSize", 6)]
public virtual BigInteger LatestShortTokenClaimableFundingAmountPerSize { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionInfo : PositionInfoBase
{
}
public class PositionInfoBase
{
[Parameter("tuple", "position", 1)] public virtual PositionProps Position { get; set; }
[Parameter("tuple", "fees", 2)] public virtual PositionFees Fees { get; set; }
[Parameter("tuple", "executionPriceResult", 3)]
public virtual ExecutionPriceResult ExecutionPriceResult { get; set; }
[Parameter("int256", "basePnlUsd", 4)] public virtual BigInteger BasePnlUsd { get; set; }
[Parameter("int256", "uncappedBasePnlUsd", 5)]
public virtual BigInteger UncappedBasePnlUsd { get; set; }
[Parameter("int256", "pnlAfterPriceImpactUsd", 6)]
public virtual BigInteger PnlAfterPriceImpactUsd { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionLiquidationFees : PositionLiquidationFeesBase { }
public class PositionLiquidationFeesBase
{
[Parameter("uint256", "liquidationFeeUsd", 1)]
public virtual BigInteger LiquidationFeeUsd { get; set; }
[Parameter("uint256", "liquidationFeeAmount", 2)]
public virtual BigInteger LiquidationFeeAmount { get; set; }
[Parameter("uint256", "liquidationFeeReceiverFactor", 3)]
public virtual BigInteger LiquidationFeeReceiverFactor { get; set; }
[Parameter("uint256", "liquidationFeeAmountForFeeReceiver", 4)]
public virtual BigInteger LiquidationFeeAmountForFeeReceiver { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionProFees : PositionProFeesBase { }
public class PositionProFeesBase
{
[Parameter("uint256", "traderTier", 1)]
public virtual BigInteger TraderTier { get; set; }
[Parameter("uint256", "traderDiscountFactor", 2)]
public virtual BigInteger TraderDiscountFactor { get; set; }
[Parameter("uint256", "traderDiscountAmount", 3)]
public virtual BigInteger TraderDiscountAmount { get; set; }
}
}

View File

@@ -0,0 +1,60 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionProps : PositionPropsBase
{
}
public class PositionPropsBase
{
[Parameter("tuple", "addresses", 1)] public virtual PositionAddresses Addresses { get; set; }
[Parameter("tuple", "numbers", 2)] public virtual PositionNumbers Numbers { get; set; }
[Parameter("tuple", "flags", 3)] public virtual PositionFlags Flags { get; set; }
}
public class PositionFlags
{
[Parameter("bool", "isLong", 1)] public virtual bool IsLong { get; set; }
}
public class PositionAddresses
{
[Parameter("address", "account", 1)] public virtual string Account { get; set; }
[Parameter("address", "market", 2)] public virtual string Market { get; set; }
[Parameter("address", "collateralToken", 3)]
public virtual string CollateralToken { get; set; }
}
public class PositionNumbers
{
[Parameter("uint256", "sizeInUsd", 1)] public virtual BigInteger SizeInUsd { get; set; }
[Parameter("uint256", "sizeInTokens", 2)]
public virtual BigInteger SizeInTokens { get; set; }
[Parameter("uint256", "collateralAmount", 3)]
public virtual BigInteger CollateralAmount { get; set; }
[Parameter("uint256", "borrowingFactor", 4)]
public virtual BigInteger BorrowingFactor { get; set; }
[Parameter("uint256", "fundingFeeAmountPerSize", 5)]
public virtual BigInteger FundingFeeAmountPerSize { get; set; }
[Parameter("uint256", "longTokenClaimableFundingAmountPerSize", 6)]
public virtual BigInteger LongTokenClaimableFundingAmountPerSize { get; set; }
[Parameter("uint256", "shortTokenClaimableFundingAmountPerSize", 7)]
public virtual BigInteger ShortTokenClaimableFundingAmountPerSize { get; set; }
[Parameter("uint256", "increasedAtTime", 8)]
public virtual BigInteger IncreasedAtTime { get; set; }
[Parameter("uint256", "decreasedAtTime", 9)]
public virtual BigInteger DecreasedAtTime { get; set; }
}
}

View File

@@ -0,0 +1,31 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionReferralFees : PositionReferralFeesBase { }
public class PositionReferralFeesBase
{
[Parameter("bytes32", "referralCode", 1)]
public virtual byte[] ReferralCode { get; set; }
[Parameter("address", "affiliate", 2)]
public virtual string Affiliate { get; set; }
[Parameter("address", "trader", 3)]
public virtual string Trader { get; set; }
[Parameter("uint256", "totalRebateFactor", 4)]
public virtual BigInteger TotalRebateFactor { get; set; }
[Parameter("uint256", "affiliateRewardFactor", 5)]
public virtual BigInteger AffiliateRewardFactor { get; set; }
[Parameter("uint256", "adjustedAffiliateRewardFactor", 6)]
public virtual BigInteger AdjustedAffiliateRewardFactor { get; set; }
[Parameter("uint256", "traderDiscountFactor", 7)]
public virtual BigInteger TraderDiscountFactor { get; set; }
[Parameter("uint256", "totalRebateAmount", 8)]
public virtual BigInteger TotalRebateAmount { get; set; }
[Parameter("uint256", "traderDiscountAmount", 9)]
public virtual BigInteger TraderDiscountAmount { get; set; }
[Parameter("uint256", "affiliateRewardAmount", 10)]
public virtual BigInteger AffiliateRewardAmount { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionType : PositionTypeBase { }
public class PositionTypeBase
{
[Parameter("tuple", "long", 1)]
public virtual CollateralType Long { get; set; }
[Parameter("tuple", "short", 2)]
public virtual CollateralType Short { get; set; }
}
}

View File

@@ -0,0 +1,17 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class PositionUiFees : PositionUiFeesBase { }
public class PositionUiFeesBase
{
[Parameter("address", "uiFeeReceiver", 1)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("uint256", "uiFeeReceiverFactor", 2)]
public virtual BigInteger UiFeeReceiverFactor { get; set; }
[Parameter("uint256", "uiFeeAmount", 3)]
public virtual BigInteger UiFeeAmount { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class SwapFees : SwapFeesBase { }
public class SwapFeesBase
{
[Parameter("uint256", "feeReceiverAmount", 1)]
public virtual BigInteger FeeReceiverAmount { get; set; }
[Parameter("uint256", "feeAmountForPool", 2)]
public virtual BigInteger FeeAmountForPool { get; set; }
[Parameter("uint256", "amountAfterFees", 3)]
public virtual BigInteger AmountAfterFees { get; set; }
[Parameter("address", "uiFeeReceiver", 4)]
public virtual string UiFeeReceiver { get; set; }
[Parameter("uint256", "uiFeeReceiverFactor", 5)]
public virtual BigInteger UiFeeReceiverFactor { get; set; }
[Parameter("uint256", "uiFeeAmount", 6)]
public virtual BigInteger UiFeeAmount { get; set; }
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
using System.Numerics;
using Nethereum.ABI.FunctionEncoding.Attributes;
namespace Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition
{
public partial class VirtualInventory : VirtualInventoryBase { }
public class VirtualInventoryBase
{
[Parameter("uint256", "virtualPoolAmountForLongToken", 1)]
public virtual BigInteger VirtualPoolAmountForLongToken { get; set; }
[Parameter("uint256", "virtualPoolAmountForShortToken", 2)]
public virtual BigInteger VirtualPoolAmountForShortToken { get; set; }
[Parameter("int256", "virtualInventoryForPositions", 3)]
public virtual BigInteger VirtualInventoryForPositions { get; set; }
}
}

View File

@@ -0,0 +1,748 @@
using System.Numerics;
using Managing.ABI.GmxV2.Reader.ContractDefinition;
using Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.Web3;
using GetAccountOrdersFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountOrdersFunction;
using GetAccountOrdersOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountOrdersOutputDTO;
using GetAccountPositionInfoListFunction =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountPositionInfoListFunction;
using GetAccountPositionInfoListOutputDTO =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountPositionInfoListOutputDTO;
using GetAccountPositionsFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountPositionsFunction;
using GetAccountPositionsOutputDTO =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAccountPositionsOutputDTO;
using GetAdlStateFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAdlStateFunction;
using GetAdlStateOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetAdlStateOutputDTO;
using GetDepositAmountOutFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetDepositAmountOutFunction;
using GetDepositFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetDepositFunction;
using GetDepositOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetDepositOutputDTO;
using GetExecutionPriceFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetExecutionPriceFunction;
using GetExecutionPriceOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetExecutionPriceOutputDTO;
using GetMarketBySaltFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketBySaltFunction;
using GetMarketBySaltOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketBySaltOutputDTO;
using GetMarketFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketFunction;
using GetMarketInfoFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketInfoFunction;
using GetMarketInfoListFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketInfoListFunction;
using GetMarketInfoListOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketInfoListOutputDTO;
using GetMarketInfoOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketInfoOutputDTO;
using GetMarketOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketOutputDTO;
using GetMarketsFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketsFunction;
using GetMarketsOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketsOutputDTO;
using GetMarketTokenPriceFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketTokenPriceFunction;
using GetMarketTokenPriceOutputDTO =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetMarketTokenPriceOutputDTO;
using GetNetPnlFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetNetPnlFunction;
using GetOpenInterestWithPnlFunction =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetOpenInterestWithPnlFunction;
using GetOrderFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetOrderFunction;
using GetOrderOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetOrderOutputDTO;
using GetPnlFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPnlFunction;
using GetPnlToPoolFactorFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPnlToPoolFactorFunction;
using GetPositionFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionFunction;
using GetPositionInfoFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionInfoFunction;
using GetPositionInfoOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionInfoOutputDTO;
using GetPositionOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionOutputDTO;
using GetPositionPnlUsdFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionPnlUsdFunction;
using GetPositionPnlUsdOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetPositionPnlUsdOutputDTO;
using GetShiftFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetShiftFunction;
using GetShiftOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetShiftOutputDTO;
using GetSwapAmountOutFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetSwapAmountOutFunction;
using GetSwapAmountOutOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetSwapAmountOutOutputDTO;
using GetSwapPriceImpactFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetSwapPriceImpactFunction;
using GetSwapPriceImpactOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetSwapPriceImpactOutputDTO;
using GetWithdrawalAmountOutFunction =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetWithdrawalAmountOutFunction;
using GetWithdrawalAmountOutOutputDTO =
Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetWithdrawalAmountOutOutputDTO;
using GetWithdrawalFunction = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetWithdrawalFunction;
using GetWithdrawalOutputDTO = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.GetWithdrawalOutputDTO;
using MarketPrices = Managing.ABI.GmxV2.SyntheticsReader.ContractDefinition.MarketPrices;
namespace Managing.ABI.GmxV2.SyntheticsReader
{
public partial class SyntheticsReaderService : ContractWeb3ServiceBase
{
public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(IWeb3 web3,
SyntheticsReaderDeployment syntheticsReaderDeployment,
CancellationTokenSource cancellationTokenSource = null)
{
return web3.Eth.GetContractDeploymentHandler<SyntheticsReaderDeployment>()
.SendRequestAndWaitForReceiptAsync(syntheticsReaderDeployment, cancellationTokenSource);
}
public static Task<string> DeployContractAsync(IWeb3 web3,
SyntheticsReaderDeployment syntheticsReaderDeployment)
{
return web3.Eth.GetContractDeploymentHandler<SyntheticsReaderDeployment>()
.SendRequestAsync(syntheticsReaderDeployment);
}
public static async Task<SyntheticsReaderService> DeployContractAndGetServiceAsync(IWeb3 web3,
SyntheticsReaderDeployment syntheticsReaderDeployment,
CancellationTokenSource cancellationTokenSource = null)
{
var receipt =
await DeployContractAndWaitForReceiptAsync(web3, syntheticsReaderDeployment, cancellationTokenSource);
return new SyntheticsReaderService(web3, receipt.ContractAddress);
}
public SyntheticsReaderService(IWeb3 web3, string contractAddress) : base(web3, contractAddress)
{
}
public Task<GetAccountOrdersOutputDTO> GetAccountOrdersQueryAsync(
GetAccountOrdersFunction getAccountOrdersFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetAccountOrdersFunction, GetAccountOrdersOutputDTO>(
getAccountOrdersFunction, blockParameter);
}
public Task<GetAccountOrdersOutputDTO> GetAccountOrdersQueryAsync(string dataStore, string account,
BigInteger start, BigInteger end, BlockParameter blockParameter = null)
{
var getAccountOrdersFunction = new GetAccountOrdersFunction();
getAccountOrdersFunction.DataStore = dataStore;
getAccountOrdersFunction.Account = account;
getAccountOrdersFunction.Start = start;
getAccountOrdersFunction.End = end;
return ContractHandler.QueryDeserializingToObjectAsync<GetAccountOrdersFunction, GetAccountOrdersOutputDTO>(
getAccountOrdersFunction, blockParameter);
}
public Task<GetAccountPositionInfoListOutputDTO> GetAccountPositionInfoListQueryAsync(
GetAccountPositionInfoListFunction getAccountPositionInfoListFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetAccountPositionInfoListFunction,
GetAccountPositionInfoListOutputDTO>(getAccountPositionInfoListFunction, blockParameter);
}
public Task<GetAccountPositionInfoListOutputDTO> GetAccountPositionInfoListQueryAsync(string dataStore,
string referralStorage, string account, List<string> markets, List<MarketPrices> marketPrices,
string uiFeeReceiver, BigInteger start, BigInteger end, BlockParameter blockParameter = null)
{
var getAccountPositionInfoListFunction = new GetAccountPositionInfoListFunction();
getAccountPositionInfoListFunction.DataStore = dataStore;
getAccountPositionInfoListFunction.ReferralStorage = referralStorage;
getAccountPositionInfoListFunction.Account = account;
getAccountPositionInfoListFunction.Markets = markets;
getAccountPositionInfoListFunction.MarketPrices = marketPrices;
getAccountPositionInfoListFunction.UiFeeReceiver = uiFeeReceiver;
getAccountPositionInfoListFunction.Start = start;
getAccountPositionInfoListFunction.End = end;
return ContractHandler
.QueryDeserializingToObjectAsync<GetAccountPositionInfoListFunction,
GetAccountPositionInfoListOutputDTO>(getAccountPositionInfoListFunction, blockParameter);
}
public Task<GetAccountPositionsOutputDTO> GetAccountPositionsQueryAsync(
GetAccountPositionsFunction getAccountPositionsFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetAccountPositionsFunction, GetAccountPositionsOutputDTO>(
getAccountPositionsFunction, blockParameter);
}
public Task<GetAccountPositionsOutputDTO> GetAccountPositionsQueryAsync(string dataStore, string account,
BigInteger start, BigInteger end, BlockParameter blockParameter = null)
{
var getAccountPositionsFunction = new GetAccountPositionsFunction();
getAccountPositionsFunction.DataStore = dataStore;
getAccountPositionsFunction.Account = account;
getAccountPositionsFunction.Start = start;
getAccountPositionsFunction.End = end;
return ContractHandler
.QueryDeserializingToObjectAsync<GetAccountPositionsFunction, GetAccountPositionsOutputDTO>(
getAccountPositionsFunction, blockParameter);
}
public Task<GetAdlStateOutputDTO> GetAdlStateQueryAsync(GetAdlStateFunction getAdlStateFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetAdlStateFunction, GetAdlStateOutputDTO>(
getAdlStateFunction, blockParameter);
}
public Task<GetAdlStateOutputDTO> GetAdlStateQueryAsync(string dataStore, string market, bool isLong,
MarketPrices prices, BlockParameter blockParameter = null)
{
var getAdlStateFunction = new GetAdlStateFunction();
getAdlStateFunction.DataStore = dataStore;
getAdlStateFunction.Market = market;
getAdlStateFunction.IsLong = isLong;
getAdlStateFunction.Prices = prices;
return ContractHandler.QueryDeserializingToObjectAsync<GetAdlStateFunction, GetAdlStateOutputDTO>(
getAdlStateFunction, blockParameter);
}
public Task<GetDepositOutputDTO> GetDepositQueryAsync(GetDepositFunction getDepositFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetDepositFunction, GetDepositOutputDTO>(
getDepositFunction, blockParameter);
}
public Task<GetDepositOutputDTO> GetDepositQueryAsync(string dataStore, byte[] key,
BlockParameter blockParameter = null)
{
var getDepositFunction = new GetDepositFunction();
getDepositFunction.DataStore = dataStore;
getDepositFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetDepositFunction, GetDepositOutputDTO>(
getDepositFunction, blockParameter);
}
public Task<BigInteger> GetDepositAmountOutQueryAsync(GetDepositAmountOutFunction getDepositAmountOutFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetDepositAmountOutFunction, BigInteger>(getDepositAmountOutFunction,
blockParameter);
}
public Task<BigInteger> GetDepositAmountOutQueryAsync(string dataStore, MarketsProps market,
MarketPrices prices, BigInteger longTokenAmount, BigInteger shortTokenAmount, string uiFeeReceiver,
byte swapPricingType, bool includeVirtualInventoryImpact, BlockParameter blockParameter = null)
{
var getDepositAmountOutFunction = new GetDepositAmountOutFunction();
getDepositAmountOutFunction.DataStore = dataStore;
getDepositAmountOutFunction.Market = market;
getDepositAmountOutFunction.Prices = prices;
getDepositAmountOutFunction.LongTokenAmount = longTokenAmount;
getDepositAmountOutFunction.ShortTokenAmount = shortTokenAmount;
getDepositAmountOutFunction.UiFeeReceiver = uiFeeReceiver;
getDepositAmountOutFunction.SwapPricingType = swapPricingType;
getDepositAmountOutFunction.IncludeVirtualInventoryImpact = includeVirtualInventoryImpact;
return ContractHandler.QueryAsync<GetDepositAmountOutFunction, BigInteger>(getDepositAmountOutFunction,
blockParameter);
}
public Task<GetExecutionPriceOutputDTO> GetExecutionPriceQueryAsync(
GetExecutionPriceFunction getExecutionPriceFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetExecutionPriceFunction, GetExecutionPriceOutputDTO>(
getExecutionPriceFunction, blockParameter);
}
public Task<GetExecutionPriceOutputDTO> GetExecutionPriceQueryAsync(string dataStore, string marketKey,
Props indexTokenPrice, BigInteger positionSizeInUsd, BigInteger positionSizeInTokens,
BigInteger sizeDeltaUsd, bool isLong, BlockParameter blockParameter = null)
{
var getExecutionPriceFunction = new GetExecutionPriceFunction();
getExecutionPriceFunction.DataStore = dataStore;
getExecutionPriceFunction.MarketKey = marketKey;
getExecutionPriceFunction.IndexTokenPrice = indexTokenPrice;
getExecutionPriceFunction.PositionSizeInUsd = positionSizeInUsd;
getExecutionPriceFunction.PositionSizeInTokens = positionSizeInTokens;
getExecutionPriceFunction.SizeDeltaUsd = sizeDeltaUsd;
getExecutionPriceFunction.IsLong = isLong;
return ContractHandler
.QueryDeserializingToObjectAsync<GetExecutionPriceFunction, GetExecutionPriceOutputDTO>(
getExecutionPriceFunction, blockParameter);
}
public Task<GetMarketOutputDTO> GetMarketQueryAsync(GetMarketFunction getMarketFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketFunction, GetMarketOutputDTO>(
getMarketFunction, blockParameter);
}
public Task<GetMarketOutputDTO> GetMarketQueryAsync(string dataStore, string key,
BlockParameter blockParameter = null)
{
var getMarketFunction = new GetMarketFunction();
getMarketFunction.DataStore = dataStore;
getMarketFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketFunction, GetMarketOutputDTO>(
getMarketFunction, blockParameter);
}
public Task<GetMarketBySaltOutputDTO> GetMarketBySaltQueryAsync(GetMarketBySaltFunction getMarketBySaltFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketBySaltFunction, GetMarketBySaltOutputDTO>(
getMarketBySaltFunction, blockParameter);
}
public Task<GetMarketBySaltOutputDTO> GetMarketBySaltQueryAsync(string dataStore, byte[] salt,
BlockParameter blockParameter = null)
{
var getMarketBySaltFunction = new GetMarketBySaltFunction();
getMarketBySaltFunction.DataStore = dataStore;
getMarketBySaltFunction.Salt = salt;
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketBySaltFunction, GetMarketBySaltOutputDTO>(
getMarketBySaltFunction, blockParameter);
}
public Task<GetMarketInfoOutputDTO> GetMarketInfoQueryAsync(GetMarketInfoFunction getMarketInfoFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketInfoFunction, GetMarketInfoOutputDTO>(
getMarketInfoFunction, blockParameter);
}
public Task<GetMarketInfoOutputDTO> GetMarketInfoQueryAsync(string dataStore, MarketPrices prices,
string marketKey, BlockParameter blockParameter = null)
{
var getMarketInfoFunction = new GetMarketInfoFunction();
getMarketInfoFunction.DataStore = dataStore;
getMarketInfoFunction.Prices = prices;
getMarketInfoFunction.MarketKey = marketKey;
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketInfoFunction, GetMarketInfoOutputDTO>(
getMarketInfoFunction, blockParameter);
}
public Task<GetMarketInfoListOutputDTO> GetMarketInfoListQueryAsync(
GetMarketInfoListFunction getMarketInfoListFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetMarketInfoListFunction, GetMarketInfoListOutputDTO>(
getMarketInfoListFunction, blockParameter);
}
public Task<GetMarketInfoListOutputDTO> GetMarketInfoListQueryAsync(string dataStore,
List<MarketPrices> marketPricesList, BigInteger start, BigInteger end, BlockParameter blockParameter = null)
{
var getMarketInfoListFunction = new GetMarketInfoListFunction();
getMarketInfoListFunction.DataStore = dataStore;
getMarketInfoListFunction.MarketPricesList = marketPricesList;
getMarketInfoListFunction.Start = start;
getMarketInfoListFunction.End = end;
return ContractHandler
.QueryDeserializingToObjectAsync<GetMarketInfoListFunction, GetMarketInfoListOutputDTO>(
getMarketInfoListFunction, blockParameter);
}
public Task<GetMarketTokenPriceOutputDTO> GetMarketTokenPriceQueryAsync(
GetMarketTokenPriceFunction getMarketTokenPriceFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetMarketTokenPriceFunction, GetMarketTokenPriceOutputDTO>(
getMarketTokenPriceFunction, blockParameter);
}
public Task<GetMarketTokenPriceOutputDTO> GetMarketTokenPriceQueryAsync(string dataStore, Props market,
Props indexTokenPrice, Props longTokenPrice, Props shortTokenPrice, byte[] pnlFactorType, bool maximize,
BlockParameter blockParameter = null)
{
var getMarketTokenPriceFunction = new GetMarketTokenPriceFunction();
getMarketTokenPriceFunction.DataStore = dataStore;
getMarketTokenPriceFunction.Market = market;
getMarketTokenPriceFunction.IndexTokenPrice = indexTokenPrice;
getMarketTokenPriceFunction.LongTokenPrice = longTokenPrice;
getMarketTokenPriceFunction.ShortTokenPrice = shortTokenPrice;
getMarketTokenPriceFunction.PnlFactorType = pnlFactorType;
getMarketTokenPriceFunction.Maximize = maximize;
return ContractHandler
.QueryDeserializingToObjectAsync<GetMarketTokenPriceFunction, GetMarketTokenPriceOutputDTO>(
getMarketTokenPriceFunction, blockParameter);
}
public Task<GetMarketsOutputDTO> GetMarketsQueryAsync(GetMarketsFunction getMarketsFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketsFunction, GetMarketsOutputDTO>(
getMarketsFunction, blockParameter);
}
public Task<GetMarketsOutputDTO> GetMarketsQueryAsync(string dataStore, BigInteger start, BigInteger end,
BlockParameter blockParameter = null)
{
var getMarketsFunction = new GetMarketsFunction();
getMarketsFunction.DataStore = dataStore;
getMarketsFunction.Start = start;
getMarketsFunction.End = end;
return ContractHandler.QueryDeserializingToObjectAsync<GetMarketsFunction, GetMarketsOutputDTO>(
getMarketsFunction, blockParameter);
}
public Task<BigInteger> GetNetPnlQueryAsync(GetNetPnlFunction getNetPnlFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetNetPnlFunction, BigInteger>(getNetPnlFunction, blockParameter);
}
public Task<BigInteger> GetNetPnlQueryAsync(string dataStore, Props market, Props indexTokenPrice,
bool maximize, BlockParameter blockParameter = null)
{
var getNetPnlFunction = new GetNetPnlFunction();
getNetPnlFunction.DataStore = dataStore;
getNetPnlFunction.Market = market;
getNetPnlFunction.IndexTokenPrice = indexTokenPrice;
getNetPnlFunction.Maximize = maximize;
return ContractHandler.QueryAsync<GetNetPnlFunction, BigInteger>(getNetPnlFunction, blockParameter);
}
public Task<BigInteger> GetOpenInterestWithPnlQueryAsync(
GetOpenInterestWithPnlFunction getOpenInterestWithPnlFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetOpenInterestWithPnlFunction, BigInteger>(
getOpenInterestWithPnlFunction, blockParameter);
}
public Task<BigInteger> GetOpenInterestWithPnlQueryAsync(string dataStore, Props market, Props indexTokenPrice,
bool isLong, bool maximize, BlockParameter blockParameter = null)
{
var getOpenInterestWithPnlFunction = new GetOpenInterestWithPnlFunction();
getOpenInterestWithPnlFunction.DataStore = dataStore;
getOpenInterestWithPnlFunction.Market = market;
getOpenInterestWithPnlFunction.IndexTokenPrice = indexTokenPrice;
getOpenInterestWithPnlFunction.IsLong = isLong;
getOpenInterestWithPnlFunction.Maximize = maximize;
return ContractHandler.QueryAsync<GetOpenInterestWithPnlFunction, BigInteger>(
getOpenInterestWithPnlFunction, blockParameter);
}
public Task<GetOrderOutputDTO> GetOrderQueryAsync(GetOrderFunction getOrderFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetOrderFunction, GetOrderOutputDTO>(
getOrderFunction, blockParameter);
}
public Task<GetOrderOutputDTO> GetOrderQueryAsync(string dataStore, byte[] key,
BlockParameter blockParameter = null)
{
var getOrderFunction = new GetOrderFunction();
getOrderFunction.DataStore = dataStore;
getOrderFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetOrderFunction, GetOrderOutputDTO>(
getOrderFunction, blockParameter);
}
public Task<BigInteger> GetPnlQueryAsync(GetPnlFunction getPnlFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetPnlFunction, BigInteger>(getPnlFunction, blockParameter);
}
public Task<BigInteger> GetPnlQueryAsync(string dataStore, Props market, Props indexTokenPrice, bool isLong,
bool maximize, BlockParameter blockParameter = null)
{
var getPnlFunction = new GetPnlFunction();
getPnlFunction.DataStore = dataStore;
getPnlFunction.Market = market;
getPnlFunction.IndexTokenPrice = indexTokenPrice;
getPnlFunction.IsLong = isLong;
getPnlFunction.Maximize = maximize;
return ContractHandler.QueryAsync<GetPnlFunction, BigInteger>(getPnlFunction, blockParameter);
}
public Task<BigInteger> GetPnlToPoolFactorQueryAsync(GetPnlToPoolFactorFunction getPnlToPoolFactorFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryAsync<GetPnlToPoolFactorFunction, BigInteger>(getPnlToPoolFactorFunction,
blockParameter);
}
public Task<BigInteger> GetPnlToPoolFactorQueryAsync(string dataStore, string marketAddress,
MarketPrices prices, bool isLong, bool maximize, BlockParameter blockParameter = null)
{
var getPnlToPoolFactorFunction = new GetPnlToPoolFactorFunction();
getPnlToPoolFactorFunction.DataStore = dataStore;
getPnlToPoolFactorFunction.MarketAddress = marketAddress;
getPnlToPoolFactorFunction.Prices = prices;
getPnlToPoolFactorFunction.IsLong = isLong;
getPnlToPoolFactorFunction.Maximize = maximize;
return ContractHandler.QueryAsync<GetPnlToPoolFactorFunction, BigInteger>(getPnlToPoolFactorFunction,
blockParameter);
}
public Task<GetPositionOutputDTO> GetPositionQueryAsync(GetPositionFunction getPositionFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetPositionFunction, GetPositionOutputDTO>(
getPositionFunction, blockParameter);
}
public Task<GetPositionOutputDTO> GetPositionQueryAsync(string dataStore, byte[] key,
BlockParameter blockParameter = null)
{
var getPositionFunction = new GetPositionFunction();
getPositionFunction.DataStore = dataStore;
getPositionFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetPositionFunction, GetPositionOutputDTO>(
getPositionFunction, blockParameter);
}
public Task<GetPositionInfoOutputDTO> GetPositionInfoQueryAsync(GetPositionInfoFunction getPositionInfoFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetPositionInfoFunction, GetPositionInfoOutputDTO>(
getPositionInfoFunction, blockParameter);
}
public Task<GetPositionInfoOutputDTO> GetPositionInfoQueryAsync(string dataStore, string referralStorage,
byte[] positionKey, MarketPrices prices, BigInteger sizeDeltaUsd, string uiFeeReceiver,
bool usePositionSizeAsSizeDeltaUsd, BlockParameter blockParameter = null)
{
var getPositionInfoFunction = new GetPositionInfoFunction();
getPositionInfoFunction.DataStore = dataStore;
getPositionInfoFunction.ReferralStorage = referralStorage;
getPositionInfoFunction.PositionKey = positionKey;
getPositionInfoFunction.Prices = prices;
getPositionInfoFunction.SizeDeltaUsd = sizeDeltaUsd;
getPositionInfoFunction.UiFeeReceiver = uiFeeReceiver;
getPositionInfoFunction.UsePositionSizeAsSizeDeltaUsd = usePositionSizeAsSizeDeltaUsd;
return ContractHandler.QueryDeserializingToObjectAsync<GetPositionInfoFunction, GetPositionInfoOutputDTO>(
getPositionInfoFunction, blockParameter);
}
public Task<GetPositionInfoListOutputDTO> GetPositionInfoListQueryAsync(
GetPositionInfoListFunction getPositionInfoListFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetPositionInfoListFunction, GetPositionInfoListOutputDTO>(
getPositionInfoListFunction, blockParameter);
}
public Task<GetPositionInfoListOutputDTO> GetPositionInfoListQueryAsync(string dataStore,
string referralStorage, List<byte[]> positionKeys, List<MarketPrices> prices, string uiFeeReceiver,
BlockParameter blockParameter = null)
{
var getPositionInfoListFunction = new GetPositionInfoListFunction();
getPositionInfoListFunction.DataStore = dataStore;
getPositionInfoListFunction.ReferralStorage = referralStorage;
getPositionInfoListFunction.PositionKeys = positionKeys;
getPositionInfoListFunction.Prices = prices;
getPositionInfoListFunction.UiFeeReceiver = uiFeeReceiver;
return ContractHandler
.QueryDeserializingToObjectAsync<GetPositionInfoListFunction, GetPositionInfoListOutputDTO>(
getPositionInfoListFunction, blockParameter);
}
public Task<GetPositionPnlUsdOutputDTO> GetPositionPnlUsdQueryAsync(
GetPositionPnlUsdFunction getPositionPnlUsdFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetPositionPnlUsdFunction, GetPositionPnlUsdOutputDTO>(
getPositionPnlUsdFunction, blockParameter);
}
public Task<GetPositionPnlUsdOutputDTO> GetPositionPnlUsdQueryAsync(string dataStore, Props market,
MarketPrices prices, byte[] positionKey, BigInteger sizeDeltaUsd, BlockParameter blockParameter = null)
{
var getPositionPnlUsdFunction = new GetPositionPnlUsdFunction();
getPositionPnlUsdFunction.DataStore = dataStore;
getPositionPnlUsdFunction.Market = market;
getPositionPnlUsdFunction.Prices = prices;
getPositionPnlUsdFunction.PositionKey = positionKey;
getPositionPnlUsdFunction.SizeDeltaUsd = sizeDeltaUsd;
return ContractHandler
.QueryDeserializingToObjectAsync<GetPositionPnlUsdFunction, GetPositionPnlUsdOutputDTO>(
getPositionPnlUsdFunction, blockParameter);
}
public Task<GetShiftOutputDTO> GetShiftQueryAsync(GetShiftFunction getShiftFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetShiftFunction, GetShiftOutputDTO>(
getShiftFunction, blockParameter);
}
public Task<GetShiftOutputDTO> GetShiftQueryAsync(string dataStore, byte[] key,
BlockParameter blockParameter = null)
{
var getShiftFunction = new GetShiftFunction();
getShiftFunction.DataStore = dataStore;
getShiftFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetShiftFunction, GetShiftOutputDTO>(
getShiftFunction, blockParameter);
}
public Task<GetSwapAmountOutOutputDTO> GetSwapAmountOutQueryAsync(
GetSwapAmountOutFunction getSwapAmountOutFunction, BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetSwapAmountOutFunction, GetSwapAmountOutOutputDTO>(
getSwapAmountOutFunction, blockParameter);
}
public Task<GetSwapAmountOutOutputDTO> GetSwapAmountOutQueryAsync(string dataStore, Props market,
MarketPrices prices, string tokenIn, BigInteger amountIn, string uiFeeReceiver,
BlockParameter blockParameter = null)
{
var getSwapAmountOutFunction = new GetSwapAmountOutFunction();
getSwapAmountOutFunction.DataStore = dataStore;
getSwapAmountOutFunction.Market = market;
getSwapAmountOutFunction.Prices = prices;
getSwapAmountOutFunction.TokenIn = tokenIn;
getSwapAmountOutFunction.AmountIn = amountIn;
getSwapAmountOutFunction.UiFeeReceiver = uiFeeReceiver;
return ContractHandler.QueryDeserializingToObjectAsync<GetSwapAmountOutFunction, GetSwapAmountOutOutputDTO>(
getSwapAmountOutFunction, blockParameter);
}
public Task<GetSwapPriceImpactOutputDTO> GetSwapPriceImpactQueryAsync(
GetSwapPriceImpactFunction getSwapPriceImpactFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetSwapPriceImpactFunction, GetSwapPriceImpactOutputDTO>(
getSwapPriceImpactFunction, blockParameter);
}
public Task<GetSwapPriceImpactOutputDTO> GetSwapPriceImpactQueryAsync(string dataStore, string marketKey,
string tokenIn, string tokenOut, BigInteger amountIn, Props tokenInPrice, Props tokenOutPrice,
BlockParameter blockParameter = null)
{
var getSwapPriceImpactFunction = new GetSwapPriceImpactFunction();
getSwapPriceImpactFunction.DataStore = dataStore;
getSwapPriceImpactFunction.MarketKey = marketKey;
getSwapPriceImpactFunction.TokenIn = tokenIn;
getSwapPriceImpactFunction.TokenOut = tokenOut;
getSwapPriceImpactFunction.AmountIn = amountIn;
getSwapPriceImpactFunction.TokenInPrice = tokenInPrice;
getSwapPriceImpactFunction.TokenOutPrice = tokenOutPrice;
return ContractHandler
.QueryDeserializingToObjectAsync<GetSwapPriceImpactFunction, GetSwapPriceImpactOutputDTO>(
getSwapPriceImpactFunction, blockParameter);
}
public Task<GetWithdrawalOutputDTO> GetWithdrawalQueryAsync(GetWithdrawalFunction getWithdrawalFunction,
BlockParameter blockParameter = null)
{
return ContractHandler.QueryDeserializingToObjectAsync<GetWithdrawalFunction, GetWithdrawalOutputDTO>(
getWithdrawalFunction, blockParameter);
}
public Task<GetWithdrawalOutputDTO> GetWithdrawalQueryAsync(string dataStore, byte[] key,
BlockParameter blockParameter = null)
{
var getWithdrawalFunction = new GetWithdrawalFunction();
getWithdrawalFunction.DataStore = dataStore;
getWithdrawalFunction.Key = key;
return ContractHandler.QueryDeserializingToObjectAsync<GetWithdrawalFunction, GetWithdrawalOutputDTO>(
getWithdrawalFunction, blockParameter);
}
public Task<GetWithdrawalAmountOutOutputDTO> GetWithdrawalAmountOutQueryAsync(
GetWithdrawalAmountOutFunction getWithdrawalAmountOutFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<GetWithdrawalAmountOutFunction, GetWithdrawalAmountOutOutputDTO>(
getWithdrawalAmountOutFunction, blockParameter);
}
public Task<GetWithdrawalAmountOutOutputDTO> GetWithdrawalAmountOutQueryAsync(string dataStore, Props market,
MarketPrices prices, BigInteger marketTokenAmount, string uiFeeReceiver, byte swapPricingType,
BlockParameter blockParameter = null)
{
var getWithdrawalAmountOutFunction = new GetWithdrawalAmountOutFunction();
getWithdrawalAmountOutFunction.DataStore = dataStore;
getWithdrawalAmountOutFunction.Market = market;
getWithdrawalAmountOutFunction.Prices = prices;
getWithdrawalAmountOutFunction.MarketTokenAmount = marketTokenAmount;
getWithdrawalAmountOutFunction.UiFeeReceiver = uiFeeReceiver;
getWithdrawalAmountOutFunction.SwapPricingType = swapPricingType;
return ContractHandler
.QueryDeserializingToObjectAsync<GetWithdrawalAmountOutFunction, GetWithdrawalAmountOutOutputDTO>(
getWithdrawalAmountOutFunction, blockParameter);
}
public Task<IsPositionLiquidatableOutputDTO> IsPositionLiquidatableQueryAsync(
IsPositionLiquidatableFunction isPositionLiquidatableFunction, BlockParameter blockParameter = null)
{
return ContractHandler
.QueryDeserializingToObjectAsync<IsPositionLiquidatableFunction, IsPositionLiquidatableOutputDTO>(
isPositionLiquidatableFunction, blockParameter);
}
public Task<IsPositionLiquidatableOutputDTO> IsPositionLiquidatableQueryAsync(string dataStore,
string referralStorage, byte[] positionKey, Props market, MarketPrices prices,
bool shouldValidateMinCollateralUsd, BlockParameter blockParameter = null)
{
var isPositionLiquidatableFunction = new IsPositionLiquidatableFunction();
isPositionLiquidatableFunction.DataStore = dataStore;
isPositionLiquidatableFunction.ReferralStorage = referralStorage;
isPositionLiquidatableFunction.PositionKey = positionKey;
isPositionLiquidatableFunction.Market = market;
isPositionLiquidatableFunction.Prices = prices;
isPositionLiquidatableFunction.ShouldValidateMinCollateralUsd = shouldValidateMinCollateralUsd;
return ContractHandler
.QueryDeserializingToObjectAsync<IsPositionLiquidatableFunction, IsPositionLiquidatableOutputDTO>(
isPositionLiquidatableFunction, blockParameter);
}
public override List<Type> GetAllFunctionTypes()
{
return new List<Type>
{
typeof(GetAccountOrdersFunction),
typeof(GetAccountPositionInfoListFunction),
typeof(GetAccountPositionsFunction),
typeof(GetAdlStateFunction),
typeof(GetDepositFunction),
typeof(GetDepositAmountOutFunction),
typeof(GetExecutionPriceFunction),
typeof(GetMarketFunction),
typeof(GetMarketBySaltFunction),
typeof(GetMarketInfoFunction),
typeof(GetMarketInfoListFunction),
typeof(GetMarketTokenPriceFunction),
typeof(GetMarketsFunction),
typeof(GetNetPnlFunction),
typeof(GetOpenInterestWithPnlFunction),
typeof(GetOrderFunction),
typeof(GetPnlFunction),
typeof(GetPnlToPoolFactorFunction),
typeof(GetPositionFunction),
typeof(GetPositionInfoFunction),
typeof(GetPositionInfoListFunction),
typeof(GetPositionPnlUsdFunction),
typeof(GetShiftFunction),
typeof(GetSwapAmountOutFunction),
typeof(GetSwapPriceImpactFunction),
typeof(GetWithdrawalFunction),
typeof(GetWithdrawalAmountOutFunction),
typeof(IsPositionLiquidatableFunction)
};
}
public override List<Type> GetAllEventTypes()
{
return new List<Type>
{
};
}
public override List<Type> GetAllErrorTypes()
{
return new List<Type>
{
};
}
}
}

View File

@@ -1,20 +1,24 @@
using System.Text.Json.Serialization;
using Managing.Api.Workers.Filters;
using Managing.Api.Workers.Workers;
using Managing.Api.WorkersExceptions;
using Managing.Application.Hubs;
using Managing.Bootstrap;
using Managing.Common;
using Managing.Core.Middleawares;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using Microsoft.OpenApi.Models;
using NSwag;
using NSwag.Generation.Processors.Security;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using OpenApiSecurityRequirement = Microsoft.OpenApi.Models.OpenApiSecurityRequirement;
using OpenApiSecurityScheme = NSwag.OpenApiSecurityScheme;
// Builder
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(System.AppContext.BaseDirectory);
builder.Configuration.SetBasePath(AppContext.BaseDirectory);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json");
@@ -32,7 +36,7 @@ builder.Host.UseSerilog((hostBuilder, loggerConfiguration) =>
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
TypeName = null,
BatchAction = ElasticOpType.Create,
MinimumLogEventLevel = Serilog.Events.LogEventLevel.Information,
MinimumLogEventLevel = LogEventLevel.Information,
DetectElasticsearchVersion = true,
RegisterTemplateFailure = RegisterTemplateRecovery.IndexAnyway,
};
@@ -80,19 +84,19 @@ builder.Services.AddSwaggerGen(options =>
{
Description = "Please insert your JWT Token into field : Bearer {your_token}",
Name = "Authorization",
Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = SecuritySchemeType.Http,
In = ParameterLocation.Header,
Scheme = "Bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new Microsoft.OpenApi.Models.OpenApiReference
Reference = new OpenApiReference
{
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
@@ -103,7 +107,7 @@ builder.Services.AddSwaggerGen(options =>
builder.WebHost.SetupDiscordBot();
builder.Services.AddHostedService<FeeWorker>();
// builder.Services.AddHostedService<PositionManagerWorker>();
builder.Services.AddHostedService<PositionManagerWorker>();
// builder.Services.AddHostedService<PositionFetcher>();
// builder.Services.AddHostedService<PricesFiveMinutesWorker>();
builder.Services.AddHostedService<PricesFifteenMinutesWorker>();

View File

@@ -1,7 +1,9 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Hubs;
using Managing.Core;
using Managing.Domain.Backtests;
using Managing.Domain.Candles;
using Managing.Domain.MoneyManagements;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -122,7 +124,9 @@ public class BacktestController : ControllerBase
if (string.IsNullOrEmpty(moneyManagementName) && moneyManagement == null)
{
throw new ArgumentException($"'{nameof(moneyManagementName)}' and '{nameof(moneyManagement)}' cannot be null or empty.", nameof(moneyManagementName));
throw new ArgumentException(
$"'{nameof(moneyManagementName)}' and '{nameof(moneyManagement)}' cannot be null or empty.",
nameof(moneyManagementName));
}
if (days > 0)
@@ -146,19 +150,23 @@ public class BacktestController : ControllerBase
if (scenario == null)
return BadRequest("No scenario found");
var localCandles = FileHelpers
.ReadJson<List<Candle>>($"{ticker.ToString()}-{timeframe.ToString()}-candles.json")
.TakeLast(500).ToList();
switch (botType)
{
case BotType.SimpleBot:
break;
case BotType.ScalpingBot:
backtestResult = _backtester.RunScalpingBotBacktest(account, moneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), balance, watchOnly, save);
timeframe, Convert.ToDouble(days), balance, watchOnly, save, initialCandles: localCandles);
break;
case BotType.FlippingBot:
backtestResult = _backtester.RunFlippingBotBacktest(account, moneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), balance, watchOnly, save);
timeframe, Convert.ToDouble(days), balance, watchOnly, save, initialCandles: localCandles);
break;
}
}
await NotifyBacktesingSubscriberAsync(backtestResult);
@@ -171,7 +179,8 @@ public class BacktestController : ControllerBase
/// <param name="backtesting">The backtest result to notify subscribers about.</param>
private async Task NotifyBacktesingSubscriberAsync(Backtest backtesting)
{
if(backtesting != null){
if (backtesting != null)
{
await _hubContext.Clients.All.SendAsync("BacktestsSubscription", backtesting);
}
}

View File

@@ -1,6 +1,6 @@
using Managing.Api.Models.Requests;
using Managing.Api.Models.Responses;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Hubs;
using Managing.Application.ManageBot.Commands;
using MediatR;
@@ -33,7 +33,8 @@ public class BotController : ControllerBase
/// <param name="mediator">Mediator for handling commands and requests.</param>
/// <param name="hubContext">SignalR hub context for real-time communication.</param>
/// <param name="backtester">Backtester for running backtests on bots.</param>
public BotController(ILogger<BotController> logger, IMediator mediator, IHubContext<BotHub> hubContext, IBacktester backtester)
public BotController(ILogger<BotController> logger, IMediator mediator, IHubContext<BotHub> hubContext,
IBacktester backtester)
{
_logger = logger;
_mediator = mediator;
@@ -50,8 +51,9 @@ public class BotController : ControllerBase
[Route("Start")]
public async Task<ActionResult<string>> Start(StartBotRequest request)
{
var result = await _mediator.Send(new StartBotCommand(request.BotType, request.BotName, request.Ticker,
request.Scenario, request.Timeframe, request.AccountName, request.MoneyManagementName, request.IsForWatchOnly));
var result = await _mediator.Send(new StartBotCommand(request.BotType, request.BotName, request.Ticker,
request.Scenario, request.Timeframe, request.AccountName, request.MoneyManagementName,
request.IsForWatchOnly));
await NotifyBotSubscriberAsync();
return Ok(result);

View File

@@ -3,6 +3,7 @@ using Managing.Application.Abstractions.Services;
using Managing.Application.Hubs;
using Managing.Application.Workers.Abstractions;
using Managing.Domain.Candles;
using Managing.Domain.Statistics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
@@ -58,10 +59,8 @@ public class DataController : ControllerBase
{
var account = await _accountService.GetAccount(accountName, true, false);
var cacheKey = string.Concat(accountName, timeframe.ToString());
var tickers = _cacheService.GetOrSave(cacheKey, () =>
{
return _exchangeService.GetTickers(account, timeframe).Result;
}, TimeSpan.FromHours(2));
var tickers = _cacheService.GetOrSave(cacheKey,
() => { return _exchangeService.GetTickers(account, timeframe).Result; }, TimeSpan.FromHours(2));
return Ok(tickers);
}
@@ -73,10 +72,8 @@ public class DataController : ControllerBase
[HttpGet("Spotlight")]
public ActionResult<SpotlightOverview> GetSpotlight()
{
var overview = _cacheService.GetOrSave(nameof(SpotlightOverview), () =>
{
return _statisticService.GetLastSpotlight(DateTime.Now.AddHours(-3));
}, TimeSpan.FromMinutes(2));
var overview = _cacheService.GetOrSave(nameof(SpotlightOverview),
() => { return _statisticService.GetLastSpotlight(DateTime.Now.AddHours(-3)); }, TimeSpan.FromMinutes(2));
if (overview?.Spotlights.Count < overview?.ScenarioCount)
{
@@ -95,7 +92,8 @@ public class DataController : ControllerBase
/// <param name="timeframe">The timeframe for the candle data.</param>
/// <returns>A list of <see cref="Candle"/> objects.</returns>
[HttpGet("GetCandles")]
public async Task<ActionResult<List<Candle>>> GetCandles(TradingExchanges exchange, Ticker ticker, DateTime startDate, Timeframe timeframe)
public async Task<ActionResult<List<Candle>>> GetCandles(TradingExchanges exchange, Ticker ticker,
DateTime startDate, Timeframe timeframe)
{
return Ok(await _exchangeService.GetCandlesInflux(exchange, ticker, startDate, timeframe));
}

View File

@@ -8,21 +8,25 @@ using Managing.Application.Hubs;
using Managing.Bootstrap;
using Managing.Common;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NSwag;
using NSwag.Generation.Processors.Security;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using OpenApiSecurityRequirement = Microsoft.OpenApi.Models.OpenApiSecurityRequirement;
using OpenApiSecurityScheme = NSwag.OpenApiSecurityScheme;
// Builder
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(System.AppContext.BaseDirectory);
builder.Configuration.SetBasePath(AppContext.BaseDirectory);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json")
.AddJsonFile($"config.{builder.Environment.EnvironmentName}.json",
optional: true, reloadOnChange: true);
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json")
.AddJsonFile($"config.{builder.Environment.EnvironmentName}.json",
optional: true, reloadOnChange: true);
builder.Configuration.AddEnvironmentVariables();
builder.Configuration.AddUserSecrets<Program>();
@@ -41,7 +45,7 @@ builder.Host.UseSerilog((hostBuilder, loggerConfiguration) =>
AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
TypeName = null,
BatchAction = ElasticOpType.Create,
MinimumLogEventLevel = Serilog.Events.LogEventLevel.Information,
MinimumLogEventLevel = LogEventLevel.Information,
DetectElasticsearchVersion = true,
RegisterTemplateFailure = RegisterTemplateRecovery.IndexAnyway,
};
@@ -65,7 +69,7 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJw
ValidIssuer = builder.Configuration["Authentication:Schemes:Bearer:ValidIssuer"],
ValidAudience = builder.Configuration["Authentication:Schemes:Bearer:ValidAudiences"],
IssuerSigningKey = new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])),
(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])),
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true
@@ -75,12 +79,12 @@ builder.Services.AddAuthorization();
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.SetIsOriginAllowed((host) => true)
.AllowAnyOrigin()
.WithOrigins("http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
.SetIsOriginAllowed((host) => true)
.AllowAnyOrigin()
.WithOrigins("http://localhost:3000/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
builder.Services.AddSignalR().AddJsonProtocol();
@@ -108,20 +112,23 @@ builder.Services.AddSwaggerGen(options =>
{
Description = "Please insert your JWT Token into field : Bearer {your_token}",
Name = "Authorization",
Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = SecuritySchemeType.Http,
In = ParameterLocation.Header,
Scheme = "Bearer",
BearerFormat = "JWT"
});
options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement{
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new Microsoft.OpenApi.Models.OpenApiSecurityScheme{
Reference = new Microsoft.OpenApi.Models.OpenApiReference{
Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]{}
new string[] { }
}
});
});
@@ -167,4 +174,4 @@ app.UseEndpoints(endpoints =>
endpoints.MapHub<CandleHub>("/candlehub");
});
app.Run();
app.Run();

View File

@@ -1,7 +1,6 @@

using Managing.Domain.Backtests;
using Managing.Domain.Backtests;
namespace Managing.Application.Abstractions;
namespace Managing.Application.Abstractions.Repositories;
public interface IBacktestRepository
{
@@ -9,4 +8,4 @@ public interface IBacktestRepository
IEnumerable<Backtest> GetBacktests();
void DeleteBacktestById(string id);
void DeleteAllBacktests();
}
}

View File

@@ -1,3 +1,7 @@
using Managing.Domain.Bots;
namespace Managing.Application.Abstractions.Repositories;
public interface IBotRepository
{
Task InsertBotAsync(BotBackup bot);

View File

@@ -5,16 +5,26 @@ using Managing.Domain.MoneyManagements;
using Managing.Domain.Scenarios;
using static Managing.Common.Enums;
namespace Managing.Application.Abstractions
namespace Managing.Application.Abstractions.Services
{
public interface IBacktester
{
Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker, Scenario scenario, Timeframe timeframe, double days, decimal balance, bool isForWatchingOnly = false, bool save = false);
Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker, Scenario scenario, Timeframe timeframe, double days, decimal balance, bool isForWatchingOnly = false, bool save = false);
Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker,
Scenario scenario, Timeframe timeframe, double days, decimal balance, bool isForWatchingOnly = false,
bool save = false, List<Candle>? initialCandles = null);
Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker,
Scenario scenario, Timeframe timeframe, double days, decimal balance, bool isForWatchingOnly = false,
bool save = false, List<Candle>? initialCandles = null);
IEnumerable<Backtest> GetBacktests();
bool DeleteBacktest(string id);
bool DeleteBacktests();
Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario, Timeframe timeframe, List<Candle> candles, decimal balance);
Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario, Timeframe timeframe, List<Candle> candles, decimal balance);
Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario,
Timeframe timeframe, List<Candle> candles, decimal balance);
Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario,
Timeframe timeframe, List<Candle> candles, decimal balance);
}
}

BIN
src/Managing.Application.Tests/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -1,9 +1,10 @@
using Managing.Application.Abstractions.Services;
using Managing.Application.Abstractions;
using Moq;
using Managing.Domain.MoneyManagements;
using static Managing.Common.Enums;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Accounts;
using Managing.Domain.MoneyManagements;
using Managing.Infrastructure.Tests;
using Moq;
using static Managing.Common.Enums;
namespace Managing.Application.Tests;
@@ -13,39 +14,31 @@ public class BaseTests
public readonly Mock<IAccountService> _accountService;
public readonly IExchangeService _exchangeService;
public readonly Mock<ITradingService> _tradingService;
public readonly Account Account;
public readonly MoneyManagement MoneyManagement;
public const string PublicAddress = "0x0425dEAb364E9121F7CA284129dA854FD5cF22eD";
public const string PrivateKey = "";
public readonly Account _account;
public BaseTests()
{
_account = PrivateKeys.GetAccount();
_accountService = new Mock<IAccountService>();
_moneyManagementService = new Mock<IMoneyManagementService>();
MoneyManagement = new MoneyManagement()
{
BalanceAtRisk = 0.30m,
Leverage = 2,
BalanceAtRisk = 0.30m, // 30%
Leverage = 2, // x2
Timeframe = Timeframe.FifteenMinutes,
StopLoss = 0.008m,
TakeProfit = 0.02m,
StopLoss = 0.008m, // 0.8%
TakeProfit = 0.02m, // 2%
Name = "Default MM"
};
_ =_moneyManagementService.Setup(m => m.GetMoneyMangement(It.IsAny<string>())).Returns(Task.FromResult(MoneyManagement));
Account = new Account()
{
Exchange = TradingExchanges.Evm,
Key = PublicAddress,
Secret = PrivateKey,
};
_ = _moneyManagementService.Setup(m => m.GetMoneyMangement(It.IsAny<string>()))
.Returns(Task.FromResult(MoneyManagement));
_accountService.Setup(a => a.GetAccount(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<bool>()))
.Returns(Task.FromResult(Account));
.Returns(Task.FromResult(_account));
_tradingService = new Mock<ITradingService>();
_exchangeService = TradingBaseTests.GetExchangeService();
}
}
}

View File

@@ -1,12 +1,16 @@
using Managing.Application.Abstractions;
using System.Collections;
using System.Diagnostics;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Application.Backtesting;
using Managing.Application.Bots.Base;
using Managing.Core;
using Managing.Domain.Candles;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Scenarios;
using Moq;
using System.Collections;
using System.Diagnostics;
using Newtonsoft.Json;
using Xunit;
using static Managing.Common.Enums;
@@ -22,7 +26,7 @@ namespace Managing.Application.Tests
private readonly string _s = "|";
private List<double> _elapsedTimes { get; set; }
public BotsTests() : base ()
public BotsTests() : base()
{
var backtestRepository = new Mock<IBacktestRepository>().Object;
var discordService = new Mock<IMessengerService>().Object;
@@ -41,17 +45,24 @@ namespace Managing.Application.Tests
}
[Theory]
[InlineData(Ticker.BTC, Timeframe.OneDay, -100)]
public void SwingBot_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe, int days)
[InlineData(Ticker.BTC, Timeframe.FifteenMinutes, -10)]
public void SwingBot_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var scenario = new Scenario("ScalpingScenario");
var scenario = new Scenario("FlippingScenario");
var strategy = ScenarioHelpers.BuildStrategy(StrategyType.RsiDivergence, timeframe, "RsiDiv", period: 14);
scenario.AddStrategy(strategy);
var localCandles =
FileHelpers.ReadJson<List<Candle>>($"{ticker.ToString()}-{timeframe.ToString()}-candles.json");
// Act
var backtestResult = _backtester.RunFlippingBotBacktest(Account, MoneyManagement, ticker, scenario, timeframe, Convert.ToDouble(days*2), 1000);
WriteCsvReport(backtestResult.GetStringReport());
var backtestResult = _backtester.RunFlippingBotBacktest(_account, MoneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), 1000, initialCandles: localCandles.TakeLast(500).ToList());
var json = JsonConvert.SerializeObject(backtestResult, Formatting.None);
File.WriteAllText($"{ticker.ToString()}-{timeframe.ToString()}-{Guid.NewGuid()}.json", json);
// WriteCsvReport(backtestResult.GetStringReport());
// Assert
Assert.True(backtestResult.FinalPnl > 0);
@@ -67,7 +78,8 @@ namespace Managing.Application.Tests
//[InlineData(Enums.Exchanges.Binance, "BTCUSDT", Timeframe.ThirtyMinutes, -4)]
//[InlineData(Enums.Exchanges.Binance, "BTCUSDT", Timeframe.FifteenMinutes, -4)]
[InlineData(Ticker.BTC, Timeframe.FifteenMinutes, -14)]
public void ScalpingBot_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe, int days)
public void ScalpingBot_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var scenario = new Scenario("ScalpingScenario");
@@ -75,7 +87,8 @@ namespace Managing.Application.Tests
scenario.AddStrategy(strategy);
// Act
var backtestResult = _backtester.RunScalpingBotBacktest(Account, MoneyManagement, ticker, scenario, timeframe, Convert.ToDouble(days), 1000);
var backtestResult = _backtester.RunScalpingBotBacktest(_account, MoneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), 1000);
//WriteCsvReport(backtestResult.GetStringReport());
// Assert
@@ -86,11 +99,13 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(Ticker.BTC, Timeframe.FifteenMinutes, -8)]
public void MacdCross_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe, int days)
public void MacdCross_Should_Return_Positiv_Profit_For_Every_Position(Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var scenario = new Scenario("ScalpingScenario");
var strategy = ScenarioHelpers.BuildStrategy(StrategyType.MacdCross, timeframe, "RsiDiv", fastPeriods: 12, slowPeriods: 26, signalPeriods: 9);
var strategy = ScenarioHelpers.BuildStrategy(StrategyType.MacdCross, timeframe, "RsiDiv", fastPeriods: 12,
slowPeriods: 26, signalPeriods: 9);
scenario.AddStrategy(strategy);
var moneyManagement = new MoneyManagement()
@@ -103,7 +118,8 @@ namespace Managing.Application.Tests
};
// Act
var backtestResult = _backtester.RunScalpingBotBacktest(Account, moneyManagement, ticker, scenario, timeframe, Convert.ToDouble(days), 1000);
var backtestResult = _backtester.RunScalpingBotBacktest(_account, moneyManagement, ticker, scenario,
timeframe, Convert.ToDouble(days), 1000);
WriteCsvReport(backtestResult.GetStringReport());
// Assert
@@ -115,7 +131,8 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(Timeframe.FifteenMinutes, -6, StrategyType.RsiDivergenceConfirm, BotType.ScalpingBot)]
//[InlineData(Timeframe.FifteenMinutes, -6, Enums.StrategyType.RsiDivergenceConfirm, Enums.BotType.FlippingBot)]
public void GetBestPeriodRsiForDivergenceFlippingBot(Timeframe timeframe, int days, StrategyType strategyType, BotType botType)
public void GetBestPeriodRsiForDivergenceFlippingBot(Timeframe timeframe, int days, StrategyType strategyType,
BotType botType)
{
var result = new List<Tuple<string, int, decimal, decimal, decimal, decimal>>();
var errors = new List<string>();
@@ -124,24 +141,27 @@ namespace Managing.Application.Tests
MaxDegreeOfParallelism = 4
};
var periodRange = new List<int>() { 2, 7};
var periodRange = new List<int>() { 2, 7 };
var stopLossRange = new List<decimal>() { 0.005m, 0.05m, 0.005m };
var takeProfitRange = new List<decimal>() { 0.01m, 0.1m, 0.02m };
var fileIdentifier = $"{strategyType}-{timeframe}";
var completedTest = 0;
var totalTests = GetTotalTrades(periodRange, stopLossRange, takeProfitRange) * Enum.GetNames(typeof(Ticker)).Length;
var totalTests = GetTotalTrades(periodRange, stopLossRange, takeProfitRange) *
Enum.GetNames(typeof(Ticker)).Length;
CleanAnalyseFile(fileIdentifier);
UpdateProgression(totalTests, completedTest);
Parallel.ForEach((Ticker[])Enum.GetValues(typeof(Ticker)), options, ticker => {
var candles = _exchangeService.GetCandles(Account, ticker, DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
Parallel.ForEach((Ticker[])Enum.GetValues(typeof(Ticker)), options, ticker =>
{
var candles = _exchangeService
.GetCandles(_account, ticker, DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
if (candles == null || candles.Count == 0)
return;
Parallel.For(periodRange[0], periodRange[1], options, i => {
Parallel.For(periodRange[0], periodRange[1], options, i =>
{
var scenario = new Scenario("ScalpingScenario");
var strategy = ScenarioHelpers.BuildStrategy(strategyType, timeframe, "RsiDiv", period: i);
scenario.AddStrategy(strategy);
@@ -150,7 +170,7 @@ namespace Managing.Application.Tests
for (decimal s = stopLossRange[0]; s < stopLossRange[1]; s += stopLossRange[2])
{
// +1% to +10% in 1%
for(decimal t = takeProfitRange[0]; t < takeProfitRange[1]; t += takeProfitRange[2])
for (decimal t = takeProfitRange[0]; t < takeProfitRange[1]; t += takeProfitRange[2])
{
var moneyManagement = new MoneyManagement()
{
@@ -165,25 +185,29 @@ namespace Managing.Application.Tests
{
var timer = new Stopwatch();
timer.Start();
var backtestResult = botType switch
{
BotType.SimpleBot => throw new NotImplementedException(),
BotType.ScalpingBot => _backtester.RunScalpingBotBacktest(Account, moneyManagement, scenario, timeframe, candles, 1000),
BotType.FlippingBot => _backtester.RunFlippingBotBacktest(Account, moneyManagement, scenario, timeframe, candles, 1000),
BotType.ScalpingBot => _backtester.RunScalpingBotBacktest(_account, moneyManagement,
scenario, timeframe, candles, 1000),
BotType.FlippingBot => _backtester.RunFlippingBotBacktest(_account, moneyManagement,
scenario, timeframe, candles, 1000),
_ => throw new NotImplementedException(),
};
timer.Stop();
if (backtestResult.FinalPnl > 0
&& (backtestResult.GrowthPercentage - backtestResult.HodlPercentage) > 30
if (backtestResult.FinalPnl > 0
&& (backtestResult.GrowthPercentage - backtestResult.HodlPercentage) > 30
&& backtestResult.Statistics.MaxDrawdown < 3)
{
var currentResult = new Tuple<string, int, decimal, decimal, decimal, decimal>(ticker.ToString(), i,
backtestResult.FinalPnl, s, t, backtestResult.GrowthPercentage - backtestResult.HodlPercentage);
var currentResult = new Tuple<string, int, decimal, decimal, decimal, decimal>(
ticker.ToString(), i,
backtestResult.FinalPnl, s, t,
backtestResult.GrowthPercentage - backtestResult.HodlPercentage);
result.Add(currentResult);
}
completedTest++;
UpdateProgression(totalTests, completedTest, timer.Elapsed.TotalSeconds);
}
@@ -199,7 +223,8 @@ namespace Managing.Application.Tests
foreach (var r in result)
{
WriteCsvAnalyse($"{r.Item1}{_s}{r.Item2}{_s}{r.Item3.ToString("0.000")}{_s}{r.Item4 * 100}{_s}{r.Item5 * 100}{_s}{r.Item6}");
WriteCsvAnalyse(
$"{r.Item1}{_s}{r.Item2}{_s}{r.Item3.ToString("0.000")}{_s}{r.Item4 * 100}{_s}{r.Item5 * 100}{_s}{r.Item6}");
}
foreach (var e in errors)
@@ -208,7 +233,8 @@ namespace Managing.Application.Tests
}
var bestResult = result.OrderByDescending(b => b.Item3).FirstOrDefault();
WriteCsvAnalyse($"Best result : {bestResult.Item1} - Rsi Period : {bestResult.Item2} - {bestResult.Item3} - SL : {bestResult.Item4}% - TP : {bestResult.Item5}%");
WriteCsvAnalyse(
$"Best result : {bestResult.Item1} - Rsi Period : {bestResult.Item2} - {bestResult.Item3} - SL : {bestResult.Item4}% - TP : {bestResult.Item5}%");
Assert.True(result.Any());
}
@@ -217,7 +243,8 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(Timeframe.OneHour, -30, StrategyType.MacdCross, BotType.FlippingBot)]
[InlineData(Timeframe.OneHour, -30, StrategyType.MacdCross, BotType.ScalpingBot)]
public void GetBestMMForMacdFlippingBot(Timeframe timeframe, int days, StrategyType strategyType, BotType botType)
public void GetBestMMForMacdFlippingBot(Timeframe timeframe, int days, StrategyType strategyType,
BotType botType)
{
var result = new List<Tuple<string, decimal, decimal, decimal, decimal>>();
var errors = new List<string>();
@@ -230,20 +257,23 @@ namespace Managing.Application.Tests
var takeProfitRange = new List<decimal>() { 0.01m, 0.1m, 0.02m };
var fileIdentifier = $"{strategyType}-{timeframe}-{botType}";
var completedTest = 0;
var totalTests = GetTotalTradeForStopLossTakeProfit(stopLossRange, takeProfitRange) * Enum.GetNames(typeof(Ticker)).Length;
var totalTests = GetTotalTradeForStopLossTakeProfit(stopLossRange, takeProfitRange) *
Enum.GetNames(typeof(Ticker)).Length;
CleanAnalyseFile(fileIdentifier);
UpdateProgression(totalTests, completedTest);
Parallel.ForEach((Ticker[])Enum.GetValues(typeof(Ticker)), options, ticker => {
var candles = _exchangeService.GetCandles(Account, ticker, DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
Parallel.ForEach((Ticker[])Enum.GetValues(typeof(Ticker)), options, ticker =>
{
var candles = _exchangeService
.GetCandles(_account, ticker, DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
if (candles == null || candles.Count == 0)
return;
var scenario = new Scenario("ScalpingScenario");
var strategy = ScenarioHelpers.BuildStrategy(strategyType, timeframe, "RsiDiv", fastPeriods: 12, slowPeriods: 26, signalPeriods: 9);
var strategy = ScenarioHelpers.BuildStrategy(strategyType, timeframe, "RsiDiv", fastPeriods: 12,
slowPeriods: 26, signalPeriods: 9);
scenario.AddStrategy(strategy);
// -0.5 to -5
@@ -268,8 +298,10 @@ namespace Managing.Application.Tests
var backtestResult = botType switch
{
BotType.SimpleBot => throw new NotImplementedException(),
BotType.ScalpingBot => _backtester.RunScalpingBotBacktest(Account, moneyManagement, scenario, timeframe, candles, 1000),
BotType.FlippingBot => _backtester.RunFlippingBotBacktest(Account, moneyManagement, scenario, timeframe, candles, 1000),
BotType.ScalpingBot => _backtester.RunScalpingBotBacktest(_account, moneyManagement,
scenario, timeframe, candles, 1000),
BotType.FlippingBot => _backtester.RunFlippingBotBacktest(_account, moneyManagement,
scenario, timeframe, candles, 1000),
_ => throw new NotImplementedException(),
};
@@ -277,8 +309,10 @@ namespace Managing.Application.Tests
&& (backtestResult.GrowthPercentage - backtestResult.HodlPercentage) > 30
&& backtestResult.Statistics.MaxDrawdown < 3)
{
var currentResult = new Tuple<string, decimal, decimal, decimal, decimal>(ticker.ToString(),
backtestResult.FinalPnl, s, t, backtestResult.GrowthPercentage - backtestResult.HodlPercentage);
var currentResult = new Tuple<string, decimal, decimal, decimal, decimal>(
ticker.ToString(),
backtestResult.FinalPnl, s, t,
backtestResult.GrowthPercentage - backtestResult.HodlPercentage);
result.Add(currentResult);
}
@@ -290,6 +324,7 @@ namespace Managing.Application.Tests
completedTest++;
errors.Add($"{ticker}{_s}{s}{_s}{t}{_s}{ex.Message}");
}
timer.Stop();
}
}
@@ -297,7 +332,8 @@ namespace Managing.Application.Tests
foreach (var r in result)
{
WriteCsvAnalyse($"{r.Item1}{_s}{r.Item2.ToString("0.000")}{_s}{r.Item3 * 100}{_s}{r.Item4 * 100}{_s}{r.Item5}");
WriteCsvAnalyse(
$"{r.Item1}{_s}{r.Item2.ToString("0.000")}{_s}{r.Item3 * 100}{_s}{r.Item4 * 100}{_s}{r.Item5}");
}
foreach (var e in errors)
@@ -306,7 +342,8 @@ namespace Managing.Application.Tests
}
var bestResult = result.OrderByDescending(b => b.Item3).FirstOrDefault();
WriteCsvAnalyse($"Best result : {bestResult.Item1} - Rsi Period : {bestResult.Item2} - {bestResult.Item3} - SL : {bestResult.Item4}% - TP : {bestResult.Item5}%");
WriteCsvAnalyse(
$"Best result : {bestResult.Item1} - Rsi Period : {bestResult.Item2} - {bestResult.Item3} - SL : {bestResult.Item4}% - TP : {bestResult.Item5}%");
Assert.True(result.Any());
}
@@ -321,8 +358,8 @@ namespace Managing.Application.Tests
{
if (!string.IsNullOrEmpty(fileIdentifier))
_analysePath += $"-{fileIdentifier}-{DateTime.Now.ToString("dd-MM-HH-mm")}.csv";
File.AppendAllLines(_analysePath , new[] { line });
File.AppendAllLines(_analysePath, new[] { line });
}
private void WriteCsvErrors(string line)
@@ -335,12 +372,14 @@ namespace Managing.Application.Tests
WriteCsvAnalyse("", fileIdentifier);
}
private decimal GetTotalTrades(List<int> periodRange, List<decimal> stopLossRange, List<decimal> takeProfitRange)
private decimal GetTotalTrades(List<int> periodRange, List<decimal> stopLossRange,
List<decimal> takeProfitRange)
{
var stopLossRangeTotalTest = stopLossRange[1] / stopLossRange[2];
var takeProfitRangeTotalTest = takeProfitRange[1] / takeProfitRange[2];
var totalTrades = GetTotalTradeForStopLossTakeProfit(stopLossRange, takeProfitRange) * stopLossRangeTotalTest * takeProfitRangeTotalTest;
var totalTrades = GetTotalTradeForStopLossTakeProfit(stopLossRange, takeProfitRange) *
stopLossRangeTotalTest * takeProfitRangeTotalTest;
return totalTrades;
}
@@ -406,4 +445,4 @@ namespace Managing.Application.Tests
}
}
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,35 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<PlatformTarget>AnyCPU</PlatformTarget>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<PlatformTarget>AnyCPU</PlatformTarget>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MathNet.Numerics" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="Microsoft.TestPlatform.AdapterUtilities" Version="17.9.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.3.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.3.1" />
<PackageReference Include="xunit" Version="2.8.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="MathNet.Numerics" Version="5.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.5"/>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0"/>
<PackageReference Include="Microsoft.TestPlatform.AdapterUtilities" Version="17.9.0"/>
<PackageReference Include="Moq" Version="4.20.70"/>
<PackageReference Include="MSTest.TestAdapter" Version="3.3.1"/>
<PackageReference Include="MSTest.TestFramework" Version="3.3.1"/>
<PackageReference Include="xunit" Version="2.8.0"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Managing.Api\Managing.Api.csproj" />
<ProjectReference Include="..\Managing.Application\Managing.Application.csproj" />
<ProjectReference Include="..\Managing.Common\Managing.Common.csproj" />
<ProjectReference Include="..\Managing.Core\Managing.Core.csproj" />
<ProjectReference Include="..\Managing.Domain\Managing.Domain.csproj" />
<ProjectReference Include="..\Managing.Infrastructure.Exchanges\Managing.Infrastructure.Exchanges.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Managing.Api\Managing.Api.csproj"/>
<ProjectReference Include="..\Managing.Application\Managing.Application.csproj"/>
<ProjectReference Include="..\Managing.Common\Managing.Common.csproj"/>
<ProjectReference Include="..\Managing.Core\Managing.Core.csproj"/>
<ProjectReference Include="..\Managing.Domain\Managing.Domain.csproj"/>
<ProjectReference Include="..\Managing.Infrastructure.Exchanges\Managing.Infrastructure.Exchanges.csproj"/>
<ProjectReference Include="..\Managing.Infrastructure.Tests\Managing.Infrastructure.Tests.csproj"/>
</ItemGroup>
<ItemGroup>
<Folder Include="Data\"/>
</ItemGroup>
<ItemGroup>
<None Update="Data\candles.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

File diff suppressed because one or more lines are too long

View File

@@ -17,9 +17,7 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Binance, Ticker.ADA, Timeframe.OneDay)]
[InlineData(TradingExchanges.Binance, Ticker.ADA, Timeframe.OneDay)]
[InlineData(TradingExchanges.Binance, Ticker.ADA, Timeframe.OneDay)]
public void Shoud_Return_Signal_On_Rsi_BullishDivergence2(TradingExchanges exchange, Ticker ticker,
public void Should_Return_Signal_On_Rsi_BullishDivergence2(TradingExchanges exchange, Ticker ticker,
Timeframe timeframe)
{
var account = GetAccount(exchange);
@@ -80,12 +78,13 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Ftx, Ticker.ADA, Timeframe.OneDay, -500)]
public void Shoud_Return_Signal_On_Macd_Cross(TradingExchanges exchange, Ticker ticker, Timeframe timeframe, int days)
public async void Shoud_Return_Signal_On_Macd_Cross(TradingExchanges exchange, Ticker ticker,
Timeframe timeframe, int days)
{
// Arrange
var account = GetAccount(exchange);
var rsiStrategy = new MACDCrossStrategy("unittest", timeframe, 12, 26, 9);
var candles = _exchangeService.GetCandles(account, ticker, DateTime.Now.AddDays(days), timeframe).Result;
var candles = await _exchangeService.GetCandles(account, ticker, DateTime.Now.AddDays(days), timeframe);
var resultSignal = new List<Signal>();
// Act
@@ -106,7 +105,8 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Ftx, Ticker.ADA, Timeframe.OneDay, -500)]
public void Shoud_Return_Signal_On_SuperTrend(TradingExchanges exchange, Ticker ticker, Timeframe timeframe, int days)
public void Shoud_Return_Signal_On_SuperTrend(TradingExchanges exchange, Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var account = GetAccount(exchange);
@@ -132,7 +132,8 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Ftx, Ticker.ADA, Timeframe.OneDay, -500)]
public void Shoud_Return_Signal_On_ChandelierExist(TradingExchanges exchange, Ticker ticker, Timeframe timeframe, int days)
public void Shoud_Return_Signal_On_ChandelierExist(TradingExchanges exchange, Ticker ticker,
Timeframe timeframe, int days)
{
// Arrange
var account = GetAccount(exchange);
@@ -147,7 +148,7 @@ namespace Managing.Application.Tests
var signals = chandelierExitStrategy.Run();
}
if (chandelierExitStrategy.Signals != null && chandelierExitStrategy.Signals.Count > 0)
if (chandelierExitStrategy.Signals is { Count: > 0 })
resultSignal.AddRange(chandelierExitStrategy.Signals);
// Assert
@@ -158,7 +159,8 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Ftx, Ticker.ADA, Timeframe.OneDay, -500)]
public void Shoud_Return_Signal_On_EmaTrend(TradingExchanges exchange, Ticker ticker, Timeframe timeframe, int days)
public void Shoud_Return_Signal_On_EmaTrend(TradingExchanges exchange, Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var account = GetAccount(exchange);
@@ -184,8 +186,9 @@ namespace Managing.Application.Tests
[Theory]
[InlineData(TradingExchanges.Ftx, Ticker.ADA, Timeframe.OneDay, -500)]
public void Shoud_Return_Signal_On_StochRsi(TradingExchanges exchange, Ticker ticker, Timeframe timeframe, int days)
[InlineData(TradingExchanges.Evm, Ticker.BTC, Timeframe.FifteenMinutes, -50)]
public void Shoud_Return_Signal_On_StochRsi(TradingExchanges exchange, Ticker ticker, Timeframe timeframe,
int days)
{
// Arrange
var account = GetAccount(exchange);
@@ -193,6 +196,10 @@ namespace Managing.Application.Tests
var candles = _exchangeService.GetCandles(account, ticker, DateTime.Now.AddDays(days), timeframe).Result;
var resultSignal = new List<Signal>();
// var json = JsonConvert.SerializeObject(candles);
// File.WriteAllText($"{ticker.ToString()}-{timeframe.ToString()}-candles.json", json);
// var json2 = FileHelpers.ReadJson<List<Candle>>($"{ticker.ToString()}-{timeframe.ToString()}-candles.json");
// Act
foreach (var candle in candles)
{
@@ -209,4 +216,4 @@ namespace Managing.Application.Tests
Assert.Contains(resultSignal, s => s.Direction == TradeDirection.Long);
}
}
}
}

View File

@@ -7,7 +7,7 @@ namespace Managing.Application.Tests;
public class WorkflowTests : BaseTests
{
[Fact]
public async void Should_Create_Workflow_with_Feed_Ticker_Flow()
public async Task Should_Create_Workflow_with_Feed_Ticker_Flow()
{
// Arrange
var workflow = new Workflow
@@ -43,11 +43,12 @@ public class WorkflowTests : BaseTests
{
Assert.False(string.IsNullOrEmpty(f.Output));
}
Assert.NotNull(workflow);
Assert.NotNull(workflow.Flows);
Assert.Single(workflow.Flows);
Assert.Equal("Feed Ticker", workflow.Name);
Assert.Equal(WorkflowUsage.Trading, workflow.Usage);
Assert.Equal("Basic trading Workflow", workflow.Description);
}
}
}
}

View File

@@ -1,4 +1,5 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Core;
using Managing.Domain.Accounts;
@@ -40,11 +41,11 @@ namespace Managing.Application.Backtesting
{
_backtestRepository.InsertBacktest(result);
}
return result;
}
public Backtest RunScalpingBotBacktest(
Account account,
public Backtest RunScalpingBotBacktest(Account account,
MoneyManagement moneyManagement,
Ticker ticker,
Scenario scenario,
@@ -52,22 +53,27 @@ namespace Managing.Application.Backtesting
double days,
decimal balance,
bool isForWatchingOnly = false,
bool save = false)
bool save = false,
List<Candle> initialCandles = null)
{
var scalpingBot = _botFactory.CreateBacktestScalpingBot(account.Name, moneyManagement, ticker, "scenario", timeframe, isForWatchingOnly);
var scalpingBot = _botFactory.CreateBacktestScalpingBot(account.Name, moneyManagement, ticker, "scenario",
timeframe, isForWatchingOnly);
scalpingBot.LoadStrategies(ScenarioHelpers.GetStrategiesFromScenario(scenario));
var candles = GetCandles(account, ticker, timeframe, days);
var result = GetBacktestingResult(ticker, scenario, timeframe, scalpingBot, candles, balance, account, moneyManagement);
var candles = initialCandles ?? GetCandles(account, ticker, timeframe, days);
var result = GetBacktestingResult(ticker, scenario, timeframe, scalpingBot, candles, balance, account,
moneyManagement);
if (save)
{
_backtestRepository.InsertBacktest(result);
}
return result;
}
private List<Candle> GetCandles(Account account, Ticker ticker, Timeframe timeframe, double days)
{
var candles = _exchangeService.GetCandlesInflux(account.Exchange, ticker, DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
var candles = _exchangeService.GetCandlesInflux(account.Exchange, ticker,
DateTime.Now.AddDays(Convert.ToDouble(days)), timeframe).Result;
if (candles == null || candles.Count == 0)
throw new Exception($"No candles for {ticker} on {account.Exchange}");
@@ -75,35 +81,46 @@ namespace Managing.Application.Backtesting
return candles;
}
public Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker, Scenario scenario, Timeframe timeframe,
double days, decimal balance, bool isForWatchingOnly = false, bool save = false)
public Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Ticker ticker,
Scenario scenario, Timeframe timeframe,
double days, decimal balance, bool isForWatchingOnly = false, bool save = false,
List<Candle> initialCandles = null)
{
var flippingBot = _botFactory.CreateBacktestFlippingBot(account.Name, moneyManagement, ticker, "scenario", timeframe, false);
var flippingBot = _botFactory.CreateBacktestFlippingBot(account.Name, moneyManagement, ticker, "scenario",
timeframe, false);
var strategy = ScenarioHelpers.GetStrategiesFromScenario(scenario);
flippingBot.LoadStrategies(ScenarioHelpers.GetStrategiesFromScenario(scenario));
var candles = GetCandles(account, ticker, timeframe, days);
var result = GetBacktestingResult(ticker, scenario, timeframe, flippingBot, candles, balance, account, moneyManagement);
var candles = initialCandles ?? GetCandles(account, ticker, timeframe, days);
var result = GetBacktestingResult(ticker, scenario, timeframe, flippingBot, candles, balance, account,
moneyManagement);
if (save)
{
_backtestRepository.InsertBacktest(result);
}
return result;
}
public Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario, Timeframe timeframe, List<Candle> candles, decimal balance)
public Backtest RunScalpingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario,
Timeframe timeframe, List<Candle> candles, decimal balance)
{
var ticker = MiscExtensions.ParseEnum<Ticker>(candles.FirstOrDefault().Ticker);
var bot = _botFactory.CreateBacktestScalpingBot(account.Name, moneyManagement, ticker, "scenario", timeframe, false);
var bot = _botFactory.CreateBacktestScalpingBot(account.Name, moneyManagement, ticker, "scenario",
timeframe, false);
bot.LoadStrategies(ScenarioHelpers.GetStrategiesFromScenario(scenario));
var result = GetBacktestingResult(ticker, scenario, timeframe, bot, candles, balance, account, moneyManagement);
var result = GetBacktestingResult(ticker, scenario, timeframe, bot, candles, balance, account,
moneyManagement);
return result;
}
public Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario, Timeframe timeframe, List<Candle> candles, decimal balance)
public Backtest RunFlippingBotBacktest(Account account, MoneyManagement moneyManagement, Scenario scenario,
Timeframe timeframe, List<Candle> candles, decimal balance)
{
var ticker = MiscExtensions.ParseEnum<Ticker>(candles.FirstOrDefault().Ticker);
var bot = _botFactory.CreateBacktestFlippingBot(account.Name, moneyManagement, ticker, "scenario", timeframe, false);
var result = GetBacktestingResult(ticker, scenario, timeframe, bot, candles, balance, account, moneyManagement);
var bot = _botFactory.CreateBacktestFlippingBot(account.Name, moneyManagement, ticker, "scenario",
timeframe, false);
var result = GetBacktestingResult(ticker, scenario, timeframe, bot, candles, balance, account,
moneyManagement);
return result;
}
@@ -137,7 +154,8 @@ namespace Managing.Application.Backtesting
var stats = TradingHelpers.GetStatistics(bot.WalletBalances);
var growthPercentage = TradingHelpers.GetGrowthFromInitalBalance(balance, finalPnl);
var hodlPercentage = TradingHelpers.GetHodlPercentage(candles[0], candles.Last());
var result = new Backtest(ticker, scenario.Name, bot.Positions, bot.Signals.ToList(), timeframe, candles, bot.BotType, account.Name)
var result = new Backtest(ticker, scenario.Name, bot.Positions, bot.Signals.ToList(), timeframe, candles,
bot.BotType, account.Name)
{
FinalPnl = finalPnl,
WinRate = winRate,
@@ -154,7 +172,6 @@ namespace Managing.Application.Backtesting
}
public IEnumerable<Backtest> GetBacktests()
{
return _backtestRepository.GetBacktests();
@@ -189,4 +206,4 @@ namespace Managing.Application.Backtesting
}
}
}
}
}

View File

@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Application.Bots;
using Managing.Common;

View File

@@ -1,4 +1,5 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Domain.MoneyManagements;
using Microsoft.Extensions.Logging;
using static Managing.Common.Enums;
@@ -13,9 +14,9 @@ public class SettingsService : ISettingsService
private readonly ILogger<SettingsService> _logger;
public SettingsService(IMoneyManagementService moneyManagementService,
IScenarioService scenarioService,
IBacktester backtester,
ILogger<SettingsService> logger)
IScenarioService scenarioService,
IBacktester backtester,
ILogger<SettingsService> logger)
{
_moneyManagementService = moneyManagementService;
_scenarioService = scenarioService;
@@ -68,6 +69,7 @@ public class SettingsService : ISettingsService
_logger.LogError(ex.Message);
return false;
}
return true;
}
@@ -94,7 +96,7 @@ public class SettingsService : ISettingsService
SetupSuperTrend(timeframe);
SetupChandelierExit(timeframe);
SetupStochRsiTrend(timeframe);
SetupStochSTCTrend(timeframe);
SetupStochSTCTrend(timeframe);
SetupEmaTrend(timeframe);
SetupEmaCross(timeframe);
}
@@ -103,11 +105,11 @@ public class SettingsService : ISettingsService
{
var name = "STCTrend";
var strategy = _scenarioService.CreateStrategy(StrategyType.Stc,
timeframe,
name,
fastPeriods: 23,
slowPeriods: 50,
cyclePeriods: 10);
timeframe,
name,
fastPeriods: 23,
slowPeriods: 50,
cyclePeriods: 10);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -115,11 +117,11 @@ public class SettingsService : ISettingsService
{
var name = "MacdCross";
var strategy = _scenarioService.CreateStrategy(StrategyType.MacdCross,
timeframe,
name,
fastPeriods: 12,
slowPeriods: 26,
signalPeriods: 9);
timeframe,
name,
fastPeriods: 12,
slowPeriods: 26,
signalPeriods: 9);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -127,9 +129,9 @@ public class SettingsService : ISettingsService
{
var name = "RsiDiv6";
var strategy = _scenarioService.CreateStrategy(StrategyType.RsiDivergence,
timeframe,
name,
period: 6);
timeframe,
name,
period: 6);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -137,9 +139,9 @@ public class SettingsService : ISettingsService
{
var name = "RsiDivConfirm6";
var strategy = _scenarioService.CreateStrategy(StrategyType.RsiDivergenceConfirm,
timeframe,
name,
period: 6);
timeframe,
name,
period: 6);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -147,10 +149,10 @@ public class SettingsService : ISettingsService
{
var name = "SuperTrend";
var strategy = _scenarioService.CreateStrategy(StrategyType.SuperTrend,
timeframe,
name,
period: 10,
multiplier: 3);
timeframe,
name,
period: 10,
multiplier: 3);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -158,22 +160,23 @@ public class SettingsService : ISettingsService
{
var name = "ChandelierExit";
var strategy = _scenarioService.CreateStrategy(StrategyType.ChandelierExit,
timeframe,
name,
period: 22,
multiplier: 3);
timeframe,
name,
period: 22,
multiplier: 3);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
private void SetupStochRsiTrend(Timeframe timeframe)
{
var name = "StochRsiTrend";
var strategy = _scenarioService.CreateStrategy(StrategyType.StochRsiTrend,
timeframe,
name,
period: 14,
stochPeriods: 14,
signalPeriods: 3,
smoothPeriods: 1);
timeframe,
name,
period: 14,
stochPeriods: 14,
signalPeriods: 3,
smoothPeriods: 1);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -181,9 +184,9 @@ public class SettingsService : ISettingsService
{
var name = "Ema200Trend";
var strategy = _scenarioService.CreateStrategy(StrategyType.EmaTrend,
timeframe,
name,
period: 200);
timeframe,
name,
period: 200);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
@@ -191,9 +194,9 @@ public class SettingsService : ISettingsService
{
var name = "Ema200Cross";
var strategy = _scenarioService.CreateStrategy(StrategyType.EmaCross,
timeframe,
name,
period: 200);
timeframe,
name,
period: 200);
_scenarioService.CreateScenario(name, new List<string> { strategy.Name });
}
}
}

View File

@@ -7,49 +7,43 @@ using static Managing.Common.Enums;
namespace Managing.Application.Trading;
public class ClosePositionCommandHandler : ICommandHandler<ClosePositionCommand, Position>
public class ClosePositionCommandHandler(
IExchangeService exchangeService,
IAccountService accountService,
ITradingService tradingService)
: ICommandHandler<ClosePositionCommand, Position>
{
private readonly IExchangeService _exchangeService;
private readonly IAccountService _accountService;
private readonly ITradingService _tradingService;
public ClosePositionCommandHandler(
IExchangeService exchangeService,
IAccountService accountService,
ITradingService tradingService)
{
_exchangeService = exchangeService;
_accountService = accountService;
_tradingService = tradingService;
}
public async Task<Position> Handle(ClosePositionCommand request)
{
// Get Trade
var account = await _accountService.GetAccount(request.Position.AccountName, false, false);
var account = await accountService.GetAccount(request.Position.AccountName, false, false);
if (request.Position == null)
{
_ = _exchangeService.CancelOrder(account, request.Position.Ticker).Result;
_ = exchangeService.CancelOrder(account, request.Position.Ticker).Result;
return request.Position;
}
var isForPaperTrading = request.Position.Initiator == PositionInitiator.PaperTrading;
var lastPrice = request.Position.Initiator == PositionInitiator.PaperTrading ?
request.ExecutionPrice.GetValueOrDefault() :
_exchangeService.GetPrice(account, request.Position.Ticker, DateTime.UtcNow);
var lastPrice = request.Position.Initiator == PositionInitiator.PaperTrading
? request.ExecutionPrice.GetValueOrDefault()
: exchangeService.GetPrice(account, request.Position.Ticker, DateTime.UtcNow);
// Close market
var closedPosition = _exchangeService.ClosePosition(account, request.Position, lastPrice, isForPaperTrading).Result;
var closeRequestedOrders = isForPaperTrading ? true : _exchangeService.CancelOrder(account, request.Position.Ticker).Result;
var closedPosition =
await exchangeService.ClosePosition(account, request.Position, lastPrice, isForPaperTrading);
var closeRequestedOrders =
isForPaperTrading || (await exchangeService.CancelOrder(account, request.Position.Ticker));
if (closeRequestedOrders || closedPosition.Status == (TradeStatus.PendingOpen | TradeStatus.Filled))
{
request.Position.Status = PositionStatus.Finished;
request.Position.ProfitAndLoss = TradingBox.GetProfitAndLoss(request.Position, closedPosition.Quantity, lastPrice);
_tradingService.UpdatePosition(request.Position);
request.Position.ProfitAndLoss =
TradingBox.GetProfitAndLoss(request.Position, closedPosition.Quantity, lastPrice,
request.Position.Open.Leverage);
tradingService.UpdatePosition(request.Position);
}
return request.Position;
}
}
}

View File

@@ -7,33 +7,30 @@ using static Managing.Common.Enums;
namespace Managing.Application.Trading
{
public class OpenPositionCommandHandler : ICommandHandler<OpenPositionRequest, Position>
public class OpenPositionCommandHandler(
IExchangeService exchangeService,
IAccountService accountService,
ITradingService tradingService)
: ICommandHandler<OpenPositionRequest, Position>
{
private readonly IExchangeService _exchangeService;
private readonly IAccountService _accountService;
private readonly ITradingService _tradingService;
public OpenPositionCommandHandler(
IExchangeService exchangeService,
IAccountService accountService,
ITradingService tradingService)
public async Task<Position> Handle(OpenPositionRequest request)
{
_exchangeService = exchangeService;
_accountService = accountService;
_tradingService = tradingService;
}
public Task<Position> Handle(OpenPositionRequest request)
{
var account = _accountService.GetAccount(request.AccountName, hideSecrets: false, getBalance: false).Result;
if (!request.IsForPaperTrading && !_exchangeService.CancelOrder(account, request.Ticker).Result)
var account = await accountService.GetAccount(request.AccountName, hideSecrets: false, getBalance: false);
if (!request.IsForPaperTrading)
{
throw new Exception($"Not able to close all orders for {request.Ticker}");
var cancelOrderResult = await exchangeService.CancelOrder(account, request.Ticker);
if (!cancelOrderResult)
{
throw new Exception($"Not able to close all orders for {request.Ticker}");
}
}
var initiator = request.IsForPaperTrading ? PositionInitiator.PaperTrading : request.Initiator;
var position = new Position(request.AccountName, request.Direction, request.Ticker, request.MoneyManagement, initiator, request.Date);
var balance = request.IsForPaperTrading ? request.Balance.GetValueOrDefault() : _exchangeService.GetBalance(account, request.IsForPaperTrading).Result;
var position = new Position(request.AccountName, request.Direction, request.Ticker, request.MoneyManagement,
initiator, request.Date);
var balance = request.IsForPaperTrading
? request.Balance.GetValueOrDefault()
: exchangeService.GetBalance(account, request.IsForPaperTrading).Result;
var balanceAtRisk = RiskHelpers.GetBalanceAtRisk(balance, request.MoneyManagement);
if (balanceAtRisk < 13)
@@ -41,11 +38,13 @@ namespace Managing.Application.Trading
throw new Exception($"Try to risk {balanceAtRisk} $ but inferior to minimum to trade");
}
var price = request.IsForPaperTrading && request.Price.HasValue ?
request.Price.Value :
_exchangeService.GetPrice(account, request.Ticker, DateTime.Now);
var price = request.IsForPaperTrading && request.Price.HasValue
? request.Price.Value
: exchangeService.GetPrice(account, request.Ticker, DateTime.Now);
var quantity = balanceAtRisk / price;
var fee = request.IsForPaperTrading ? request.Fee.GetValueOrDefault() : _tradingService.GetFee(account, request.IsForPaperTrading);
var fee = request.IsForPaperTrading
? request.Fee.GetValueOrDefault()
: tradingService.GetFee(account, request.IsForPaperTrading);
var expectedStatus = GetExpectedStatus(request);
position.Open = TradingPolicies.OpenPosition(expectedStatus).Execute(
@@ -53,18 +52,18 @@ namespace Managing.Application.Trading
{
var openPrice = request.IsForPaperTrading || request.Price.HasValue
? request.Price.Value
: _exchangeService.GetBestPrice(account, request.Ticker, price, quantity, request.Direction);
: exchangeService.GetBestPrice(account, request.Ticker, price, quantity, request.Direction);
var trade = _exchangeService.OpenTrade(
account,
request.Ticker,
request.Direction,
openPrice,
quantity,
request.MoneyManagement.Leverage,
TradeType.Limit,
isForPaperTrading: request.IsForPaperTrading,
currentDate: request.Date).Result;
var trade = exchangeService.OpenTrade(
account,
request.Ticker,
request.Direction,
openPrice,
quantity,
request.MoneyManagement.Leverage,
TradeType.Limit,
isForPaperTrading: request.IsForPaperTrading,
currentDate: request.Date).Result;
trade.Fee = TradingHelpers.GetFeeAmount(fee, openPrice * quantity, account.Exchange);
return trade;
@@ -73,11 +72,12 @@ namespace Managing.Application.Trading
if (IsOpenTradeHandled(position.Open.Status, account.Exchange) && !request.IgnoreSLTP.GetValueOrDefault())
{
var closeDirection = request.Direction == TradeDirection.Long ? TradeDirection.Short : TradeDirection.Long;
var closeDirection = request.Direction == TradeDirection.Long
? TradeDirection.Short
: TradeDirection.Long;
// Stop loss
position.StopLoss = _exchangeService.BuildEmptyTrade(
position.StopLoss = exchangeService.BuildEmptyTrade(
request.Ticker,
RiskHelpers.GetStopLossPrice(request.Direction, position.Open.Price, request.MoneyManagement),
position.Open.Quantity,
@@ -87,10 +87,11 @@ namespace Managing.Application.Trading
request.Date,
TradeStatus.PendingOpen);
position.StopLoss.Fee = TradingHelpers.GetFeeAmount(fee, position.StopLoss.Price * position.StopLoss.Quantity, account.Exchange);
position.StopLoss.Fee = TradingHelpers.GetFeeAmount(fee,
position.StopLoss.Price * position.StopLoss.Quantity, account.Exchange);
// Take profit
position.TakeProfit1 = _exchangeService.BuildEmptyTrade(
position.TakeProfit1 = exchangeService.BuildEmptyTrade(
request.Ticker,
RiskHelpers.GetTakeProfitPrice(request.Direction, position.Open.Price, request.MoneyManagement),
quantity,
@@ -100,13 +101,16 @@ namespace Managing.Application.Trading
request.Date,
TradeStatus.PendingOpen);
position.TakeProfit1.Fee = TradingHelpers.GetFeeAmount(fee, position.TakeProfit1.Price * position.TakeProfit1.Quantity, account.Exchange);
position.TakeProfit1.Fee = TradingHelpers.GetFeeAmount(fee,
position.TakeProfit1.Price * position.TakeProfit1.Quantity, account.Exchange);
}
position.Status = IsOpenTradeHandled(position.Open.Status, account.Exchange) ? position.Status : PositionStatus.Rejected;
_tradingService.InsertPosition(position);
position.Status = IsOpenTradeHandled(position.Open.Status, account.Exchange)
? position.Status
: PositionStatus.Rejected;
tradingService.InsertPosition(position);
return Task.FromResult(position);
return position;
}
private static TradeStatus GetExpectedStatus(OpenPositionRequest request)
@@ -122,7 +126,7 @@ namespace Managing.Application.Trading
private static bool IsOpenTradeHandled(TradeStatus tradeStatus, TradingExchanges exchange)
{
return tradeStatus == TradeStatus.Filled
|| (exchange == TradingExchanges.Evm && tradeStatus == TradeStatus.Requested);
|| (exchange == TradingExchanges.Evm && tradeStatus == TradeStatus.Requested);
}
}
}
}

View File

@@ -76,7 +76,6 @@ public class TradingService : ITradingService
}
public Scenario GetScenarioByName(string scenario)
{
return _tradingRepository.GetScenarioByName(scenario);
@@ -126,7 +125,8 @@ public class TradingService : ITradingService
if (quantityInPosition > 0)
{
// Position still open
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.Open.Quantity, lastPrice);
position.ProfitAndLoss =
TradingBox.GetProfitAndLoss(position, position.Open.Quantity, lastPrice, position.Open.Leverage);
_logger.LogInformation($"Position is still open - PNL : {position.ProfitAndLoss.Realized} $");
_logger.LogInformation($"Requested trades : {orders.Count}");
}
@@ -138,7 +138,8 @@ public class TradingService : ITradingService
// SL hit
_logger.LogInformation($"Stop loss is filled on exchange.");
position.StopLoss.SetStatus(TradeStatus.Filled);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.StopLoss.Quantity, position.StopLoss.Price);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.StopLoss.Quantity,
position.StopLoss.Price, position.Open.Leverage);
_ = _exchangeService.CancelOrder(account, position.Ticker);
}
else if (orders.All(o => o.TradeType != TradeType.TakeProfit))
@@ -147,19 +148,22 @@ public class TradingService : ITradingService
if (position.TakeProfit1.Status == TradeStatus.Filled && position.TakeProfit2 != null)
{
position.TakeProfit2.SetStatus(TradeStatus.Filled);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.TakeProfit2.Quantity, position.TakeProfit2.Price);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.TakeProfit2.Quantity,
position.TakeProfit2.Price, 1);
_logger.LogInformation($"TakeProfit 2 is filled on exchange.");
}
else
{
position.TakeProfit1.SetStatus(TradeStatus.Filled);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.TakeProfit1.Quantity, position.TakeProfit1.Price);
position.ProfitAndLoss = TradingBox.GetProfitAndLoss(position, position.TakeProfit1.Quantity,
position.TakeProfit1.Price, 1);
_logger.LogInformation($"TakeProfit 1 is filled on exchange.");
}
}
else
{
_logger.LogInformation($"Position closed manually or forced close by exchange because quantity in position is below 0.");
_logger.LogInformation(
$"Position closed manually or forced close by exchange because quantity in position is below 0.");
position.Status = PositionStatus.Finished;
if (orders.Any()) await _exchangeService.CancelOrder(account, position.Ticker);
@@ -202,10 +206,8 @@ public class TradingService : ITradingService
return 0.000665M;
}
return _cacheService.GetOrSave($"Fee-{account.Exchange}", () =>
{
return _tradingRepository.GetFee(TradingExchanges.Evm)?.Cost ?? 0m;
}, TimeSpan.FromHours(2));
return _cacheService.GetOrSave($"Fee-{account.Exchange}",
() => { return _tradingRepository.GetFee(TradingExchanges.Evm)?.Cost ?? 0m; }, TimeSpan.FromHours(2));
}
public void UpdatePosition(Position position)
@@ -246,7 +248,6 @@ public class TradingService : ITradingService
{
await ManageTrader(a, availableTickers);
}
}
_cacheService.SaveValue(key, aqip, TimeSpan.FromMinutes(10));
@@ -255,8 +256,10 @@ public class TradingService : ITradingService
public IEnumerable<Trader> GetTradersWatch()
{
var watchAccount = _statisticRepository.GetBestTraders();
var customWatchAccount = _accountService.GetAccounts(true, false).Where(a => a.Type == AccountType.Watch).ToList().MapToTraders();
watchAccount.AddRange(customWatchAccount.Where(a => !watchAccount.Any(w => w.Address.Equals(a.Address, StringComparison.InvariantCultureIgnoreCase))));
var customWatchAccount = _accountService.GetAccounts(true, false).Where(a => a.Type == AccountType.Watch)
.ToList().MapToTraders();
watchAccount.AddRange(customWatchAccount.Where(a =>
!watchAccount.Any(w => w.Address.Equals(a.Address, StringComparison.InvariantCultureIgnoreCase))));
return watchAccount;
}
@@ -279,14 +282,16 @@ public class TradingService : ITradingService
{
if (oldTrade != null)
{
_logger.LogInformation($"[{shortAddress}][{ticker}] Trader previously got a position open but the position was close by trader");
_logger.LogInformation(
$"[{shortAddress}][{ticker}] Trader previously got a position open but the position was close by trader");
await _messengerService.SendClosedPosition(a.Account.Address, oldTrade);
a.Trades.Remove(oldTrade);
}
}
else if ((newTrade != null && oldTrade == null) || (newTrade.Quantity > oldTrade.Quantity))
{
_logger.LogInformation($"[{shortAddress}][{ticker}] Trader increase {newTrade.Direction} by {newTrade.Quantity - (oldTrade?.Quantity ?? 0)} with leverage {newTrade.Leverage} at {newTrade.Price} leverage.");
_logger.LogInformation(
$"[{shortAddress}][{ticker}] Trader increase {newTrade.Direction} by {newTrade.Quantity - (oldTrade?.Quantity ?? 0)} with leverage {newTrade.Leverage} at {newTrade.Price} leverage.");
var index = a.Trades.IndexOf(oldTrade);
if (index != -1)
@@ -307,12 +312,14 @@ public class TradingService : ITradingService
var decreaseAmount = oldTrade.Quantity - newTrade.Quantity;
var index = a.Trades.IndexOf(oldTrade);
a.Trades[index] = newTrade;
_logger.LogInformation($"[{a.Account.Address.Substring(0, 6)}][{ticker}] Trader decrease position but didnt close it {decreaseAmount}");
_logger.LogInformation(
$"[{a.Account.Address.Substring(0, 6)}][{ticker}] Trader decrease position but didnt close it {decreaseAmount}");
await _messengerService.SendDecreasePosition(a.Account.Address, newTrade, decreaseAmount);
}
else
{
_logger.LogInformation($"[{shortAddress}][{ticker}] No change - Quantity still {newTrade.Quantity}");
_logger.LogInformation(
$"[{shortAddress}][{ticker}] No change - Quantity still {newTrade.Quantity}");
}
}
catch (Exception ex)
@@ -324,7 +331,7 @@ public class TradingService : ITradingService
private List<TraderFollowup> GetAccountsQuantityInPosition(IEnumerable<Trader> watchAccount)
{
var result = new List<TraderFollowup> ();
var result = new List<TraderFollowup>();
foreach (var account in watchAccount)
{
var trader = SetupFollowUp(account);
@@ -352,4 +359,4 @@ public class TradingService : ITradingService
public List<Trade> Trades { get; set; }
public List<string> PositionIdentifiers { get; set; }
}
}
}

View File

@@ -1,6 +1,7 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Application.Workflows.Flows.Feeds;
using Managing.Application.Workflows.Flows.Strategies;
using Managing.Application.Workflows.Flows.Trading;
using Managing.Domain.Workflows;
using Managing.Domain.Workflows.Synthetics;
@@ -15,7 +16,8 @@ public class FlowFactory : IFlowFactory
private readonly ITradingService _tradingService;
private readonly IAccountService _accountService;
public FlowFactory(IExchangeService exchangeService, ICacheService cacheService, ITradingService tradingService, IAccountService accountService)
public FlowFactory(IExchangeService exchangeService, ICacheService cacheService, ITradingService tradingService,
IAccountService accountService)
{
_exchangeService = exchangeService;
_cacheService = cacheService;
@@ -29,16 +31,18 @@ public class FlowFactory : IFlowFactory
{
FlowType.FeedTicker => new FeedTicker(_exchangeService),
FlowType.RsiDivergence => new RsiDiv(),
FlowType.OpenPosition => new OpenPosition(_exchangeService, _cacheService, _accountService, _tradingService),
FlowType.OpenPosition => new OpenPosition(_exchangeService, _cacheService, _accountService,
_tradingService),
_ => throw new NotImplementedException(),
};
flow.Children = new List<IFlow>();
flow.Parameters = new List<FlowParameter>();
foreach (var parameter in request.Parameters)
foreach (var parameter in request.Parameters)
{
if (!flow.Parameters.Any(p => p.Name == parameter.Name)) {
if (!flow.Parameters.Any(p => p.Name == parameter.Name))
{
flow.Parameters.Add(new FlowParameter
{
Name = parameter.Name,
@@ -46,6 +50,7 @@ public class FlowFactory : IFlowFactory
});
}
}
return flow;
}
}
}

View File

@@ -4,7 +4,7 @@ using Managing.Domain.Workflows;
using Newtonsoft.Json;
using static Managing.Common.Enums;
namespace Managing.Application.Workflows.Flows.Feeds;
namespace Managing.Application.Workflows.Flows.Strategies;
public class RsiDiv : FlowBase
{
@@ -36,7 +36,7 @@ public class RsiDiv : FlowBase
Output = JsonConvert.SerializeObject(strategy.Signals);
if(Children != null && Children.Count > 0)
if (Children != null && Children.Count > 0)
{
foreach (var child in Children)
{
@@ -62,4 +62,4 @@ public class RsiDivParameters
{
public int Period { get; set; }
public Timeframe Timeframe { get; set; }
}
}

View File

@@ -2,6 +2,7 @@
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Application.Workflows.Flows.Feeds;
using Managing.Application.Workflows.Flows.Strategies;
using Managing.Application.Workflows.Flows.Trading;
using Managing.Domain.Workflows;
using Managing.Domain.Workflows.Synthetics;
@@ -14,7 +15,7 @@ public class WorkflowService : IWorkflowService
private readonly IExchangeService _exchangeService;
private readonly IFlowFactory _flowFactory;
private readonly ICacheService _cacheService;
private readonly ITradingService _tradingService;
private readonly ITradingService _tradingService;
private readonly IAccountService _accountService;
public WorkflowService(
@@ -50,10 +51,9 @@ public class WorkflowService : IWorkflowService
}
catch (Exception ex)
{
throw;
}
return Map(workflowRequest);
}
@@ -122,5 +122,4 @@ public class WorkflowService : IWorkflowService
return Task.FromResult(availableFlows.AsEnumerable());
}
}
}

View File

@@ -1,56 +1,57 @@
using FluentValidation;
using Managing.Application.Shared.Behaviours;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using Managing.Infrastructure.Exchanges;
using Managing.Infrastructure.Storage;
using Managing.Infrastructure.Databases.MongoDb;
using Microsoft.Extensions.Options;
using Managing.Application.Trading;
using Managing.Infrastructure.Messengers.Discord;
using Managing.Infrastructure.Evm;
using Discord.WebSocket;
using Microsoft.AspNetCore.Hosting;
using Discord.Commands;
using Managing.Application.Backtesting;
using Managing.Application.Scenarios;
using Managing.Application.MoneyManagements;
using Managing.Application.Accounts;
using Managing.Application.Abstractions;
using Managing.Application.Shared;
using Managing.Infrastructure.Databases;
using Managing.Infrastructure.Databases.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.InfluxDb;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Exchanges.Abstractions;
using Managing.Infrastructure.Exchanges.Exchanges;
using Managing.Application.Users;
using Managing.Infrastructure.Evm.Subgraphs;
using Managing.Application.ManageBot.Commands;
using Managing.Application.Trading.Commands;
using Managing.Domain.Trades;
using Managing.Application.Workers.Abstractions;
using Managing.Application.Workers;
using System.Reflection;
using Binance.Net.Clients;
using Binance.Net.Interfaces.Clients;
using Managing.Infrastructure.Evm.Services;
using Managing.Application.Workflows;
using Discord.Commands;
using Discord.WebSocket;
using FluentValidation;
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Application.Accounts;
using Managing.Application.Backtesting;
using Managing.Application.Bots.Base;
using Managing.Application.ManageBot;
using Managing.Application.ManageBot.Commands;
using Managing.Application.MoneyManagements;
using Managing.Application.Scenarios;
using Managing.Application.Shared;
using Managing.Application.Shared.Behaviours;
using Managing.Application.Trading;
using Managing.Application.Trading.Commands;
using Managing.Application.Users;
using Managing.Application.Workers;
using Managing.Application.Workers.Abstractions;
using Managing.Application.Workflows;
using Managing.Domain.Trades;
using Managing.Infrastructure.Databases;
using Managing.Infrastructure.Databases.InfluxDb;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using Managing.Infrastructure.Evm;
using Managing.Infrastructure.Evm.Services;
using Managing.Infrastructure.Evm.Subgraphs;
using Managing.Infrastructure.Exchanges;
using Managing.Infrastructure.Exchanges.Abstractions;
using Managing.Infrastructure.Exchanges.Exchanges;
using Managing.Infrastructure.Messengers.Discord;
using Managing.Infrastructure.Storage;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Managing.Bootstrap;
public static class ApiBootstrap
{
private static readonly Assembly ApplicationAssembly = typeof(StartBotCommand).GetTypeInfo().Assembly;
public static IServiceCollection RegisterApiDependencies(this IServiceCollection services, IConfiguration configuration)
public static IServiceCollection RegisterApiDependencies(this IServiceCollection services,
IConfiguration configuration)
{
return services
.AddApplication()
@@ -66,7 +67,7 @@ public static class ApiBootstrap
services.AddSingleton<IBacktester, Backtester>();
services.AddSingleton<IScenarioService, ScenarioService>();
services.AddSingleton<IMoneyManagementService, MoneyManagementService>();
services.AddSingleton<IAccountService, AccountService>();
services.AddSingleton<IAccountService, AccountService>();
services.AddSingleton<IStatisticService, StatisticService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<IUserService, UserService>();
@@ -82,12 +83,12 @@ public static class ApiBootstrap
{
// Database
services.AddSingleton<IManagingDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<ManagingDatabaseSettings>>().Value);
sp.GetRequiredService<IOptions<ManagingDatabaseSettings>>().Value);
services.AddTransient(typeof(IMongoRepository<>), typeof(MongoRepository<>));
services.AddSingleton<IInfluxDbSettings>(sp =>
sp.GetRequiredService<IOptions<InfluxDbSettings>>().Value);
sp.GetRequiredService<IOptions<InfluxDbSettings>>().Value);
// Evm
services.AddGbcFeed();
@@ -103,7 +104,7 @@ public static class ApiBootstrap
services.AddTransient<IBacktestRepository, BacktestRepository>();
services.AddTransient<ITradingRepository, TradingRepository>();
services.AddTransient<ISettingsRepository, SettingsRepository>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IStatisticRepository, StatisticRepository>();
services.AddTransient<IWorkflowRepository, WorkflowRepository>();
services.AddTransient<IBotRepository, BotRepository>();
@@ -159,4 +160,4 @@ public static class ApiBootstrap
.AddHostedService<DiscordService>();
});
}
}
}

View File

@@ -3,43 +3,45 @@ using Binance.Net.Interfaces.Clients;
using Kraken.Net.Clients;
using Kraken.Net.Interfaces.Clients;
using Managing.Application.Abstractions;
using Managing.Application.Accounts;
using Managing.Application.Workers;
using Managing.Application.Workers.Abstractions;
using Managing.Infrastructure.Exchanges;
using Managing.Infrastructure.Databases;
using Managing.Infrastructure.Databases.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.MongoDb;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Managing.Infrastructure.Databases.InfluxDb;
using Managing.Application.Abstractions.Repositories;
using Managing.Application.Abstractions.Services;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Evm.Subgraphs;
using Managing.Infrastructure.Evm;
using Managing.Infrastructure.Storage;
using Managing.Infrastructure.Exchanges.Abstractions;
using Managing.Infrastructure.Exchanges.Exchanges;
using Managing.Application.Trading;
using Managing.Application.Accounts;
using Managing.Application.Backtesting;
using Managing.Application.Bots.Base;
using Managing.Application.ManageBot;
using Managing.Application.MoneyManagements;
using Managing.Application.Scenarios;
using Managing.Application.Shared;
using Managing.Infrastructure.Messengers.Discord;
using Managing.Application.Trading;
using Managing.Application.Trading.Commands;
using Managing.Application.Workers;
using Managing.Application.Workers.Abstractions;
using Managing.Domain.Trades;
using Managing.Infrastructure.Databases;
using Managing.Infrastructure.Databases.InfluxDb;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Configurations;
using Managing.Infrastructure.Evm;
using Managing.Infrastructure.Evm.Services;
using Managing.Application.Bots.Base;
using Managing.Application.ManageBot;
using Managing.Infrastructure.Evm.Subgraphs;
using Managing.Infrastructure.Exchanges;
using Managing.Infrastructure.Exchanges.Abstractions;
using Managing.Infrastructure.Exchanges.Exchanges;
using Managing.Infrastructure.Messengers.Discord;
using Managing.Infrastructure.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Managing.Bootstrap;
public static class WorkersBootstrap
{
public static IServiceCollection RegisterWorkersDependencies(this IServiceCollection services, IConfiguration configuration)
public static IServiceCollection RegisterWorkersDependencies(this IServiceCollection services,
IConfiguration configuration)
{
return services
.AddApplication()
@@ -56,7 +58,7 @@ public static class WorkersBootstrap
services.AddSingleton<IWorkerService, WorkerService>();
services.AddSingleton<IAccountService, AccountService>();
services.AddSingleton<IStatisticService, StatisticService>();
services.AddSingleton<ITradingService, TradingService>();
services.AddSingleton<ITradingService, TradingService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<IBacktester, Backtester>();
services.AddSingleton<IBotService, BotService>();
@@ -71,12 +73,12 @@ public static class WorkersBootstrap
{
// Database
services.AddSingleton<IManagingDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<ManagingDatabaseSettings>>().Value);
sp.GetRequiredService<IOptions<ManagingDatabaseSettings>>().Value);
services.AddTransient(typeof(IMongoRepository<>), typeof(MongoRepository<>));
services.AddSingleton<IInfluxDbSettings>(sp =>
sp.GetRequiredService<IOptions<InfluxDbSettings>>().Value);
services.AddTransient<IInfluxDbRepository, InfluxDbRepository>();
// Evm
@@ -117,4 +119,4 @@ public static class WorkersBootstrap
return services;
}
}
}

View File

@@ -44,9 +44,22 @@
public const string POOL_AMOUNT_KEY = "POOL_AMOUNT";
public const string MARKET_DISABLED_KEY = "IS_MARKET_DISABLED";
public const string MAX_PNL_FACTOR_FOR_TRADERS = "MAX_PNL_FACTOR_FOR_TRADERS";
public const string ACCOUNT_ORDER_LIST_KEY = "ACCOUNT_ORDER_LIST";
public const string DEPOSIT_GAS_LIMIT_KEY = "DEPOSIT_GAS_LIMIT";
public const string WITHDRAWAL_GAS_LIMIT_KEY = "WITHDRAWAL_GAS_LIMIT";
public const string SHIFT_GAS_LIMIT_KEY = "SHIFT_GAS_LIMIT";
public const string SINGLE_SWAP_GAS_LIMIT_KEY = "SINGLE_SWAP_GAS_LIMIT";
public const string SWAP_ORDER_GAS_LIMIT_KEY = "SWAP_ORDER_GAS_LIMIT";
public const string INCREASE_ORDER_GAS_LIMIT_KEY = "INCREASE_ORDER_GAS_LIMIT";
public const string DECREASE_ORDER_GAS_LIMIT_KEY = "DECREASE_ORDER_GAS_LIMIT";
public const string ESTIMATED_GAS_FEE_BASE_AMOUNT = "ESTIMATED_GAS_FEE_BASE_AMOUNT_V2_1";
public const string ESTIMATED_GAS_FEE_PER_ORACLE_PRICE = "ESTIMATED_GAS_FEE_PER_ORACLE_PRICE";
public const string ESTIMATED_GAS_FEE_MULTIPLIER_FACTOR = "ESTIMATED_GAS_FEE_MULTIPLIER_FACTOR";
public class Config
{
public const string OracleKeeperUrl = "https://arbitrum-v2-1-api.gmxinfra.io";
public static readonly HashSet<Enums.Ticker> DeltaNeutralTickers = new()
{
Enums.Ticker.BTC,
@@ -61,6 +74,11 @@
Enums.Ticker.PEPE,
Enums.Ticker.WIF,
};
public static class Decimals
{
public const int USD = 30;
}
}
public class TokenAddress

View File

@@ -7,7 +7,8 @@ public static class Enums
Binance,
Kraken,
Ftx,
Evm
Evm,
GmxV2
}
public enum GmxOrderType

View File

@@ -0,0 +1,24 @@
using System.Reflection;
using System.Text.Json;
namespace Managing.Core;
public static class FileHelpers
{
public static T ReadJson<T>(string path)
{
string assemblyLocation = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyLocation);
if (assemblyDirectory != null)
{
var pathToReadFrom = Path.Combine(assemblyDirectory, path);
// Reads the content of the JSON file.
var json = File.ReadAllText(pathToReadFrom);
return JsonSerializer.Deserialize<T>(json);
}
return default;
}
}

View File

@@ -1,16 +1,18 @@
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
namespace Managing.Api.WorkersExceptions;
namespace Managing.Core.Middleawares;
public class GlobalErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public GlobalErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
@@ -22,6 +24,7 @@ public class GlobalErrorHandlingMiddleware
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
HttpStatusCode status;
@@ -60,4 +63,4 @@ public class GlobalErrorHandlingMiddleware
context.Response.StatusCode = (int)status;
return context.Response.WriteAsync(exceptionResult);
}
}
}

View File

@@ -1,5 +1,7 @@
using static Managing.Common.Enums;
namespace Managing.Domain.Bots;
public class BotBackup
{
public string Name { get; set; }

View File

@@ -1,5 +1,4 @@
using Managing.Application.Strategies;
using Managing.Domain.Strategies;
using Managing.Domain.Strategies;
using static Managing.Common.Enums;
namespace Managing.Domain.Scenarios;
@@ -14,16 +13,25 @@ public static class ScenarioHelpers
IStrategy result = strategy.Type switch
{
StrategyType.StDev => new StDevContext(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.RsiDivergence => new RSIDivergenceStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.RsiDivergenceConfirm => new RSIDivergenceConfirmStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.MacdCross => new MACDCrossStrategy(strategy.Name, strategy.Timeframe, strategy.FastPeriods.Value, strategy.SlowPeriods.Value, strategy.SignalPeriods.Value),
StrategyType.RsiDivergence => new RSIDivergenceStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value),
StrategyType.RsiDivergenceConfirm => new RSIDivergenceConfirmStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value),
StrategyType.MacdCross => new MACDCrossStrategy(strategy.Name, strategy.Timeframe,
strategy.FastPeriods.Value, strategy.SlowPeriods.Value, strategy.SignalPeriods.Value),
StrategyType.EmaCross => new EmaCrossStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.ThreeWhiteSoldiers => new ThreeWhiteSoldiersStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.SuperTrend => new SuperTrendStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value, strategy.Multiplier.Value),
StrategyType.ChandelierExit => new ChandelierExitStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value, strategy.Multiplier.Value),
StrategyType.ThreeWhiteSoldiers => new ThreeWhiteSoldiersStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value),
StrategyType.SuperTrend => new SuperTrendStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value, strategy.Multiplier.Value),
StrategyType.ChandelierExit => new ChandelierExitStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value, strategy.Multiplier.Value),
StrategyType.EmaTrend => new EmaTrendStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value),
StrategyType.StochRsiTrend => new StochRsiTrendStrategy(strategy.Name, strategy.Timeframe, strategy.Period.Value, strategy.StochPeriods.Value, strategy.SignalPeriods.Value, strategy.SmoothPeriods.Value),
StrategyType.Stc => new STCStrategy(strategy.Name, strategy.Timeframe, strategy.CyclePeriods.Value, strategy.FastPeriods.Value, strategy.SlowPeriods.Value),
StrategyType.StochRsiTrend => new StochRsiTrendStrategy(strategy.Name, strategy.Timeframe,
strategy.Period.Value, strategy.StochPeriods.Value, strategy.SignalPeriods.Value,
strategy.SmoothPeriods.Value),
StrategyType.Stc => new STCStrategy(strategy.Name, strategy.Timeframe, strategy.CyclePeriods.Value,
strategy.FastPeriods.Value, strategy.SlowPeriods.Value),
_ => throw new NotImplementedException(),
};
@@ -63,11 +71,13 @@ public static class ScenarioHelpers
{
strategy.Period = period.Value;
}
break;
case StrategyType.MacdCross:
if (!fastPeriods.HasValue || !slowPeriods.HasValue || !signalPeriods.HasValue)
{
throw new Exception($"Missing fastPeriods or slowPeriods or signalPeriods, for {strategy.Type} strategy type");
throw new Exception(
$"Missing fastPeriods or slowPeriods or signalPeriods, for {strategy.Type} strategy type");
}
else
{
@@ -75,6 +85,7 @@ public static class ScenarioHelpers
strategy.SlowPeriods = slowPeriods;
strategy.SignalPeriods = signalPeriods;
}
break;
break;
case StrategyType.ThreeWhiteSoldiers:
@@ -90,6 +101,7 @@ public static class ScenarioHelpers
strategy.Period = period;
strategy.Multiplier = multiplier;
}
break;
case StrategyType.StochRsiTrend:
if (!period.HasValue
@@ -97,7 +109,8 @@ public static class ScenarioHelpers
|| !signalPeriods.HasValue
|| !smoothPeriods.HasValue)
{
throw new Exception($"Missing period, stochPeriods, signalPeriods, smoothPeriods for {strategy.Type} strategy type");
throw new Exception(
$"Missing period, stochPeriods, signalPeriods, smoothPeriods for {strategy.Type} strategy type");
}
else
{
@@ -106,11 +119,13 @@ public static class ScenarioHelpers
strategy.SignalPeriods = signalPeriods;
strategy.SmoothPeriods = smoothPeriods;
}
break;
case StrategyType.Stc:
if (!fastPeriods.HasValue || !slowPeriods.HasValue || !cyclePeriods.HasValue)
{
throw new Exception($"Missing fastPeriods or slowPeriods or cyclePeriods, for {strategy.Type} strategy type");
throw new Exception(
$"Missing fastPeriods or slowPeriods or cyclePeriods, for {strategy.Type} strategy type");
}
else
{
@@ -118,6 +133,7 @@ public static class ScenarioHelpers
strategy.SlowPeriods = slowPeriods;
strategy.CyclePeriods = cyclePeriods;
}
break;
default:
break;
@@ -145,4 +161,4 @@ public static class ScenarioHelpers
_ => throw new NotImplementedException(),
};
}
}
}

View File

@@ -9,7 +9,8 @@ namespace Managing.Domain.Shared.Helpers;
public static class TradingBox
{
public static Signal GetSignal(HashSet<Candle> newCandles, HashSet<IStrategy> strategies, HashSet<Signal> previousSignal)
public static Signal GetSignal(HashSet<Candle> newCandles, HashSet<IStrategy> strategies,
HashSet<Signal> previousSignal)
{
var signalOnCandles = new HashSet<Signal>();
foreach (var strategy in strategies)
@@ -35,10 +36,12 @@ public static class TradingBox
return null;
var data = newCandles.First();
return ComputeSignals(strategies, signalOnCandles, MiscExtensions.ParseEnum<Ticker>(data.Ticker), data.Timeframe);
return ComputeSignals(strategies, signalOnCandles, MiscExtensions.ParseEnum<Ticker>(data.Ticker),
data.Timeframe);
}
public static Signal ComputeSignals(HashSet<IStrategy> strategies, HashSet<Signal> signalOnCandles, Ticker ticker, Timeframe timeframe)
public static Signal ComputeSignals(HashSet<IStrategy> strategies, HashSet<Signal> signalOnCandles, Ticker ticker,
Timeframe timeframe)
{
Signal signal = null;
if (strategies.Count > 1)
@@ -49,34 +52,36 @@ public static class TradingBox
var validContext = true;
if (contextStrategiesCount > 0 &&
signalOnCandles.Count(s => s.SignalType == SignalType.Context) != contextStrategiesCount)
signalOnCandles.Count(s => s.SignalType == SignalType.Context) != contextStrategiesCount)
{
validContext = false;
}
if (signals.All(s => s.Direction == TradeDirection.Long) && trendSignal.All(t => t.Direction == TradeDirection.Long) && validContext)
if (signals.All(s => s.Direction == TradeDirection.Long) &&
trendSignal.All(t => t.Direction == TradeDirection.Long) && validContext)
{
signal = new Signal(
ticker,
TradeDirection.Long,
Confidence.High,
signals.Last().Candle,
signals.Last().Date,
signals.Last().Exchange,
timeframe,
StrategyType.Composite, SignalType.Signal);
ticker,
TradeDirection.Long,
Confidence.High,
signals.Last().Candle,
signals.Last().Date,
signals.Last().Exchange,
timeframe,
StrategyType.Composite, SignalType.Signal);
}
else if (signals.All(s => s.Direction == TradeDirection.Short) && trendSignal.All(t => t.Direction == TradeDirection.Short) && validContext)
else if (signals.All(s => s.Direction == TradeDirection.Short) &&
trendSignal.All(t => t.Direction == TradeDirection.Short) && validContext)
{
signal = new Signal(
ticker,
TradeDirection.Short,
Confidence.High,
signals.Last().Candle,
signals.Last().Date,
signals.Last().Exchange,
timeframe,
StrategyType.Composite, SignalType.Signal);
ticker,
TradeDirection.Short,
Confidence.High,
signals.Last().Candle,
signals.Last().Date,
signals.Last().Exchange,
timeframe,
StrategyType.Composite, SignalType.Signal);
}
}
else
@@ -88,7 +93,8 @@ public static class TradingBox
return signal;
}
public static MoneyManagement GetBestMoneyManagement(List<Candle> candles, List<Position> positions, MoneyManagement originMoneyManagement)
public static MoneyManagement GetBestMoneyManagement(List<Candle> candles, List<Position> positions,
MoneyManagement originMoneyManagement)
{
// Foreach positions, identitify the price when the position is open
// Then, foreach candles, get the maximum price before the next position
@@ -120,11 +126,13 @@ public static class TradingBox
return moneyManagement;
}
public static (decimal Stoploss, decimal TakeProfit) GetBestSLTPForPosition(List<Candle> candles, Position position, Position nextPosition)
public static (decimal Stoploss, decimal TakeProfit) GetBestSLTPForPosition(List<Candle> candles, Position position,
Position nextPosition)
{
var stopLoss = 0M;
var takeProfit = 0M;
var candlesBeforeNextPosition = candles.Where(c => c.Date >= position.Date && c.Date <= (nextPosition == null ? candles.Last().Date : nextPosition.Date));
var candlesBeforeNextPosition = candles.Where(c =>
c.Date >= position.Date && c.Date <= (nextPosition == null ? candles.Last().Date : nextPosition.Date));
if (position.OriginDirection == TradeDirection.Long)
{
@@ -140,7 +148,7 @@ public static class TradingBox
stopLoss = GetPercentageFromEntry(position.Open.Price, maxPrice);
takeProfit = GetPercentageFromEntry(position.Open.Price, minPrice);
}
return (stopLoss, takeProfit);
}
@@ -149,13 +157,18 @@ public static class TradingBox
return Math.Abs(100 - ((100 * price) / entry));
}
public static ProfitAndLoss GetProfitAndLoss(Position position, decimal quantity, decimal price)
public static ProfitAndLoss GetProfitAndLoss(Position position, decimal quantity, decimal price, decimal leverage)
{
var orders = new List<Tuple<decimal, decimal>>
{
new Tuple<decimal, decimal>(position.Open.Quantity, position.Open.Price),
new Tuple<decimal, decimal>(-quantity, price)
};
return new ProfitAndLoss(orders, position.OriginDirection);
{
new Tuple<decimal, decimal>(position.Open.Quantity, position.Open.Price),
new Tuple<decimal, decimal>(-quantity, price)
};
var pnl = new ProfitAndLoss(orders, position.OriginDirection);
// Apply leverage on the realized pnl
pnl.Realized = pnl.Realized * leverage;
return pnl;
}
}
}

View File

@@ -1,38 +1,30 @@
using Managing.Domain.Scenarios;
using System.ComponentModel.DataAnnotations;
using Managing.Common;
using Managing.Domain.Scenarios;
using Managing.Domain.Strategies;
using System.ComponentModel.DataAnnotations;
using static Managing.Common.Enums;
namespace Managing.Domain.Statistics;
public class SpotlightOverview
{
[Required]
public List<Spotlight> Spotlights { get; set; }
[Required]
public DateTime DateTime { get; set; }
[Required] public List<Spotlight> Spotlights { get; set; }
[Required] public DateTime DateTime { get; set; }
public Guid Identifier { get; set; }
public int ScenarioCount { get; set; }
}
public class Spotlight
{
[Required]
public Scenario Scenario { get; set; }
[Required]
public List<TickerSignal> TickerSignals { get; set; }
[Required] public Scenario Scenario { get; set; }
[Required] public List<TickerSignal> TickerSignals { get; set; }
}
public class TickerSignal
{
[Required]
public Ticker Ticker { get; set; }
[Required]
public List<Signal> FiveMinutes { get; set; }
[Required]
public List<Signal> FifteenMinutes { get; set; }
[Required]
public List<Signal> OneHour { get; set; }
[Required]
public List<Signal> FourHour { get; set; }
[Required]
public List<Signal> OneDay { get; set; }
[Required] public Enums.Ticker Ticker { get; set; }
[Required] public List<Signal> FiveMinutes { get; set; }
[Required] public List<Signal> FifteenMinutes { get; set; }
[Required] public List<Signal> OneHour { get; set; }
[Required] public List<Signal> FourHour { get; set; }
[Required] public List<Signal> OneDay { get; set; }
}

View File

@@ -1,11 +1,10 @@
using Managing.Core;
using Managing.Domain.Shared.Rules;
using Managing.Domain.Strategies;
using Managing.Domain.Strategies.Base;
using Skender.Stock.Indicators;
using static Managing.Common.Enums;
namespace Managing.Application.Strategies;
namespace Managing.Domain.Strategies;
public class EmaCrossStrategy : EmaBaseStrategy
{
@@ -28,20 +27,20 @@ public class EmaCrossStrategy : EmaBaseStrategy
{
var ema = Candles.GetEma(Period.Value).ToList();
var emaCandles = MapEmaToCandle(ema, Candles.TakeLast(Period.Value));
if (ema.Count == 0)
return null;
var previousCandle = emaCandles[0];
foreach (var currentCandle in emaCandles.Skip(1))
{
if (previousCandle.Close > (decimal)currentCandle.Ema &&
if (previousCandle.Close > (decimal)currentCandle.Ema &&
currentCandle.Close < (decimal)currentCandle.Ema)
{
AddSignal(currentCandle, Timeframe, TradeDirection.Short, Confidence.Medium);
}
if (previousCandle.Close < (decimal)currentCandle.Ema &&
if (previousCandle.Close < (decimal)currentCandle.Ema &&
currentCandle.Close > (decimal)currentCandle.Ema)
{
AddSignal(currentCandle, Timeframe, TradeDirection.Long, Confidence.Medium);
@@ -60,10 +59,11 @@ public class EmaCrossStrategy : EmaBaseStrategy
private void AddSignal(CandleEma candleSignal, Timeframe timeframe, TradeDirection direction, Confidence confidence)
{
var signal = new Signal(MiscExtensions.ParseEnum<Ticker>(candleSignal.Ticker), direction, confidence, candleSignal, candleSignal.Date, candleSignal.Exchange, timeframe, Type, SignalType);
var signal = new Signal(MiscExtensions.ParseEnum<Ticker>(candleSignal.Ticker), direction, confidence,
candleSignal, candleSignal.Date, candleSignal.Exchange, timeframe, Type, SignalType);
if (!Signals.Any(s => s.Identifier == signal.Identifier))
{
Signals.AddItem(signal);
}
}
}
}

View File

@@ -1,10 +1,9 @@
using Managing.Domain.Candles;
using Managing.Domain.Shared.Rules;
using Managing.Domain.Strategies;
using Managing.Domain.Strategies.Rules;
using static Managing.Common.Enums;
namespace Managing.Application.Strategies
namespace Managing.Domain.Strategies
{
public class ThreeWhiteSoldiersStrategy : Strategy
{
@@ -52,4 +51,4 @@ namespace Managing.Application.Strategies
}
}
}
}
}

View File

@@ -1,4 +1,4 @@
using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Repositories;
using Managing.Domain.Backtests;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
@@ -35,4 +35,4 @@ public class BacktestRepository : IBacktestRepository
{
_backtestRepository.InsertOne(MongoMappers.Map(backtest));
}
}
}

View File

@@ -1,4 +1,6 @@
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Application.Abstractions.Repositories;
using Managing.Domain.Bots;
using Managing.Infrastructure.Databases.MongoDb;
using Managing.Infrastructure.Databases.MongoDb.Abstractions;
using Managing.Infrastructure.Databases.MongoDb.Collections;

View File

@@ -1,8 +1,10 @@
using InfluxDB.Client.Writes;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Writes;
using Managing.Application.Abstractions.Repositories;
using Managing.Core;
using Managing.Domain.Candles;
using Managing.Infrastructure.Databases.InfluxDb;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Models;
using Microsoft.Extensions.Logging;
using static Managing.Common.Enums;
@@ -30,14 +32,14 @@ public class CandleRepository : ICandleRepository
var results = await _influxDbRepository.QueryAsync(async query =>
{
var flux = $"from(bucket:\"{_priceBucket}\") " +
$"|> range(start: {start:s}Z) " +
$"|> filter(fn: (r) => r[\"exchange\"] == \"{exchange}\")" +
$"|> filter(fn: (r) => r[\"ticker\"] == \"{ticker}\")" +
$"|> filter(fn: (r) => r[\"timeframe\"] == \"{timeframe}\")" +
$"|> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")";
$"|> range(start: {start:s}Z) " +
$"|> filter(fn: (r) => r[\"exchange\"] == \"{exchange}\")" +
$"|> filter(fn: (r) => r[\"ticker\"] == \"{ticker}\")" +
$"|> filter(fn: (r) => r[\"timeframe\"] == \"{timeframe}\")" +
$"|> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")";
var prices = await query.QueryAsync<PriceDto>(flux, _influxDbRepository.Organization);
return prices.Select(price => PriceHelpers.Map(price)).ToList();
return prices.Select(price => PriceHelpers.Map(price)).ToList();
});
return results;
@@ -51,13 +53,13 @@ public class CandleRepository : ICandleRepository
var results = await _influxDbRepository.QueryAsync(async query =>
{
var flux = $"from(bucket:\"{_priceBucket}\") " +
$"|> range(start: {start:s}Z, stop: now()) " +
$"|> filter(fn: (r) => r[\"_measurement\"] == \"price\")" +
$"|> filter(fn: (r) => r[\"exchange\"] == \"{exchange}\")" +
$"|> filter(fn: (r) => r[\"timeframe\"] == \"{timeframe}\")" +
$"|> keep(columns: [\"ticker\"])" +
$"|> distinct()";
$"|> range(start: {start:s}Z, stop: now()) " +
$"|> filter(fn: (r) => r[\"_measurement\"] == \"price\")" +
$"|> filter(fn: (r) => r[\"exchange\"] == \"{exchange}\")" +
$"|> filter(fn: (r) => r[\"timeframe\"] == \"{timeframe}\")" +
$"|> keep(columns: [\"ticker\"])" +
$"|> distinct()";
var tickers = new List<Ticker>();
var records = await query.QueryAsync(flux, _influxDbRepository.Organization);
records.ForEach(table =>
@@ -65,7 +67,8 @@ public class CandleRepository : ICandleRepository
var fluxRecords = table.Records;
fluxRecords.ForEach(fluxRecord =>
{
tickers.AddItem(MiscExtensions.ParseEnum<Ticker>(fluxRecord.GetValueByKey("ticker").ToString()));
tickers.AddItem(
MiscExtensions.ParseEnum<Ticker>(fluxRecord.GetValueByKey("ticker").ToString()));
});
});
@@ -82,7 +85,7 @@ public class CandleRepository : ICandleRepository
PriceDto price = PriceHelpers.Map(candle);
write.WriteMeasurement(
price,
InfluxDB.Client.Api.Domain.WritePrecision.Ns,
WritePrecision.Ns,
_priceBucket,
_influxDbRepository.Organization);
});
@@ -95,11 +98,11 @@ public class CandleRepository : ICandleRepository
var point = PointData.Measurement("");
PriceDto price = PriceHelpers.Map(candle);
point.Tag("", "");
point.Timestamp(price.OpenTime, InfluxDB.Client.Api.Domain.WritePrecision.Ns);
point.Timestamp(price.OpenTime, WritePrecision.Ns);
write.WritePoint(
point,
_priceBucket,
_influxDbRepository.Organization);
});
}
}
}

View File

@@ -1,6 +1,6 @@
using InfluxDB.Client;
namespace Managing.Infrastructure.Databases;
namespace Managing.Infrastructure.Databases.InfluxDb.Abstractions;
public interface IInfluxDbRepository
{
@@ -8,4 +8,4 @@ public interface IInfluxDbRepository
Task<T> QueryAsync<T>(Func<QueryApi, Task<T>> action);
void Write(Action<WriteApi> action);
}
}

View File

@@ -1,8 +1,8 @@
namespace Managing.Infrastructure.Databases.Abstractions;
namespace Managing.Infrastructure.Databases.InfluxDb.Abstractions;
public interface IInfluxDbSettings
{
string Url { get; set; }
string Token { get; set; }
string Organization { get; set; }
}
}

View File

@@ -1,5 +1,5 @@
using InfluxDB.Client;
using Managing.Infrastructure.Databases.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;
namespace Managing.Infrastructure.Databases.InfluxDb;
@@ -10,7 +10,7 @@ public class InfluxDbRepository : IInfluxDbRepository
public string Organization { get; set; }
public InfluxDbRepository(IInfluxDbSettings settings)
{
{
_token = settings.Token;
_url = settings.Url;
Organization = settings.Organization;

View File

@@ -1,10 +1,10 @@
using Managing.Infrastructure.Databases.Abstractions;
using Managing.Infrastructure.Databases.InfluxDb.Abstractions;
namespace Managing.Infrastructure.Databases.InfluxDb.Models;
public class InfluxDbSettings : IInfluxDbSettings
{
public string Url { get ; set; }
public string Url { get; set; }
public string Token { get; set; }
public string Organization { get; set; }
}
}

View File

@@ -1,8 +1,8 @@
namespace Managing.Infrastructure.Databases.MongoDb
namespace Managing.Infrastructure.Databases.MongoDb.Configurations
{
public interface IManagingDatabaseSettings
{
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}
}

View File

@@ -1,7 +1,7 @@
namespace Managing.Infrastructure.Databases.MongoDb;
namespace Managing.Infrastructure.Databases.MongoDb.Configurations;
public class ManagingDatabaseSettings : IManagingDatabaseSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
}

View File

@@ -1,5 +1,6 @@
using Managing.Domain.Accounts;
using Managing.Domain.Backtests;
using Managing.Domain.Bots;
using Managing.Domain.Candles;
using Managing.Domain.MoneyManagements;
using Managing.Domain.Scenarios;

Some files were not shown because too many files have changed in this diff Show More