using Binance.TradeRobot.Business.Extensions; using Binance.TradeRobot.Common.DI; using Binance.TradeRobot.Common.Extensions; using Binance.TradeRobot.Model.Base; using Binance.TradeRobot.Model.Db; using Binance.TradeRobot.Model.Dto; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using System.Data.Common; using Yitter.IdGenerator; namespace Binance.TradeRobot.Business { [BatchRegistration(ServiceLifetime.Singleton, RegistrationType.Self)] public class RobotBusiness : BaseBusiness { public RobotBusiness(IFreeSql fsql, NLogManager logManager, IIdGenerator idGenerator, IMemoryCache memoryCache) : base(fsql, logManager, idGenerator, memoryCache) { } /// /// 检查机器人注册条件 /// /// /// /// private void CheckRobotRegister(AddRobotRequest addRobotRequest, out ExchangeAPIKey exchangeAPIKey) { exchangeAPIKey = null; if (string.IsNullOrEmpty(addRobotRequest.Symbol) || addRobotRequest.ExchangeAPIKeyId == 0) throw new BusinessException("参数不全"); exchangeAPIKey = fsql.Select(addRobotRequest.ExchangeAPIKeyId).ToOne(); if (exchangeAPIKey == null) throw new BusinessException("选择的APIKey不存在"); if (exchangeAPIKey.RobotId != null) throw new BusinessException("APIKey已被其他机器人使用"); var accountId = exchangeAPIKey.AccountId; if (fsql.Select().InnerJoin((ea, ek, r) => ea.Id == ek.AccountId) .LeftJoin((ea, ek, r) => ek.RobotId == r.Id) .Where((ea, ek, r) => ea.Id == accountId && r.Symbol == addRobotRequest.Symbol).Any()) throw new BusinessException("同一个交易所账号下只允许存在一个交易对"); } private Robot CreateRobot(AddRobotRequest addRobotRequest) { return new Robot() { Id = idGenerator.NewLong(), Symbol = addRobotRequest.Symbol, TradePolicy = addRobotRequest.TradePolicy, BusinessType = addRobotRequest.TradePolicy.GetBusinessType(), ExchangeId = addRobotRequest.ExchangeId, }; } private RobotAccount CreateRobotAccount(long robotId) { return new RobotAccount() { Id = idGenerator.NewLong(), RobotId = robotId }; } private void ExecuteAddRobotWithTran(Robot robot, RobotAccount robotAccount, long exchangeAPIKeyId, DbTransaction tran) { fsql.Insert(robot).WithTransaction(tran).ExecuteAffrows(); fsql.Insert(robotAccount).WithTransaction(tran).ExecuteAffrows(); fsql.Update(exchangeAPIKeyId).WithTransaction(tran).Set(ek => ek.RobotId, robot.Id).ExecuteAffrows(); } /// /// 添加金字塔策略机器人 /// /// public void AddPyramidPolicyRobot(AddPyramidPolicyRobotRequest addPyramidPolicyRobotRequest) { CheckRobotRegister(addPyramidPolicyRobotRequest, out ExchangeAPIKey exchangeAPIKey); var robot = CreateRobot(addPyramidPolicyRobotRequest); var robotAccount = CreateRobotAccount(robot.Id); var pyramidPolicy = addPyramidPolicyRobotRequest.Map(); pyramidPolicy.Id = idGenerator.NewLong(); pyramidPolicy.RobotId = robot.Id; fsql.Transaction(() => { var tran = fsql.Ado.TransactionCurrentThread; ExecuteAddRobotWithTran(robot, robotAccount, addPyramidPolicyRobotRequest.ExchangeAPIKeyId, tran); fsql.Insert(pyramidPolicy).ExecuteAffrows(); }); //调整仓位杠杆倍数 } } }