using Binance.TradeRobot.Model.Base;
using Binance.TradeRobot.Model.Db;
using Microsoft.Extensions.Caching.Memory;
using SDKAdapter.Model;
using System;
using System.Collections.Generic;
using System.Threading;
using Yitter.IdGenerator;
namespace Binance.TradeRobot.Business
{
public class BaseSpotOrderPublishBusiness : BaseBusiness
{
protected DingBusiness dingBusiness;
protected RobotBusiness robotBusiness;
protected UserBusiness userBusiness;
protected ExchangeBusiness exchangeBusiness;
public BaseSpotOrderPublishBusiness(IFreeSql fsql,
NLogManager logManager,
IIdGenerator idGenerator,
IMemoryCache memoryCache,
DingBusiness dingBusiness,
RobotBusiness robotBusiness,
UserBusiness userBusiness,
ExchangeBusiness exchangeBusiness) : base(fsql, logManager, idGenerator, memoryCache)
{
this.dingBusiness = dingBusiness;
this.robotBusiness = robotBusiness;
this.userBusiness = userBusiness;
this.exchangeBusiness = exchangeBusiness;
}
///
/// 检查订单是否存在
///
///
/// 订单不存在异常
protected void CheckOrderExists(long orderId)
{
var tryCount = 3;
while (tryCount > 0)
{
var isOrderExists = fsql.Select(orderId).Any();
if (!isOrderExists)
{
tryCount--;
Thread.Sleep(3000);
continue;
}
return;
}
throw new BusinessException("订单不存在");
}
protected void HandleError(Exception ex,
List logList,
string loggerName,
long robotId,
long orderId,
string step)
{
logList.Add(new ExecutionLog()
{
Id = idGenerator.NewLong(),
SourceSingal = Enums.SingalType.订单推送,
RobotId = robotId,
CreateTime = DateTime.Now,
Content = ex.Message,
OrderId = orderId
});
try { fsql.Insert(logList).ExecuteAffrows(); } catch { }
var errorMsg = $"交易警报,{Enums.SingalType.订单推送},{loggerName},robot {robotId},order {orderId},{step}";
logManager.GetLogger(loggerName).Error(ex, errorMsg);
dingBusiness.Send($"{errorMsg} {ex.Message}");
}
///
/// 创建客户端订单号
///
///
///
///
protected string CreateClientOrderId(long robotId, Enums.TradePolicy tradePolicy)
{
var guid = Guid.NewGuid();
var random = new Random(guid.GetHashCode());
return $"{Convert.ToChar(random.Next(97, 123))}{guid.ToString().Substring(0, 4)}_{robotId}_{(int)tradePolicy}";
}
}
}