[BOT] Pool system eingeführt

This commit is contained in:
darkeye 2025-02-14 11:27:05 +01:00
parent 4ecba91489
commit edd68e31d0
7 changed files with 182 additions and 57 deletions

View File

@ -45,6 +45,11 @@ export default class TradingBot {
*/ */
#transactions = []; #transactions = [];
/**
* @type {Map<string, number>}
*/
#activeTransactionPerPoolCounter = new Map();
/** /**
* @type {Transaction[]} * @type {Transaction[]}
*/ */
@ -119,8 +124,8 @@ export default class TradingBot {
this.#api.subscribeBalanceChanges(); this.#api.subscribeBalanceChanges();
this.#api.requestBalances(); this.#api.requestBalances();
this.#api.requestAccountInformation(); this.#api.requestAccountInformation();
this.#loadTransactions();
this.#loadWorker(); this.#loadWorker();
this.#loadTransactions();
this.#worker.forEach(worker => { this.#worker.forEach(worker => {
this.#registerTradingPair(worker.getTradingPair()); this.#registerTradingPair(worker.getTradingPair());
worker.init(this.#logger, this.#config.getDataDirectory(), this); worker.init(this.#logger, this.#config.getDataDirectory(), this);
@ -323,6 +328,7 @@ export default class TradingBot {
} }
this.#transactionHistory.push(transaction); this.#transactionHistory.push(transaction);
this.#transactions.splice(index, 1); this.#transactions.splice(index, 1);
this.#updateTransactionsPerPoolCounter(this.#worker.get(transaction.initiator).getPool(), -1);
} }
transaction.phase = nextTransactionPhase; transaction.phase = nextTransactionPhase;
@ -377,7 +383,11 @@ export default class TradingBot {
* @param {number} price * @param {number} price
*/ */
requestBuy(worker, quantity, price) { requestBuy(worker, quantity, price) {
if(this.#config.getUsdTradeLimit() / this.#config.getPerTradeLimit() <= this.#transactions.length){ console.log("Open transactions in pool '" + worker.getPool() + "': " + this.#activeTransactionPerPoolCounter.get(worker.getPool()));
if (
this.#activeTransactionPerPoolCounter.get(worker.getPool()) != null
&& this.#config.getUsdTradeLimit() / this.#config.getPerTradeLimit() <= this.#activeTransactionPerPoolCounter.get(worker.getPool())
) {
return; return;
} }
@ -385,6 +395,7 @@ export default class TradingBot {
transaction.buySettings = new TransactionSettings(price, this.#config.getPerTradeLimit() / price); transaction.buySettings = new TransactionSettings(price, this.#config.getPerTradeLimit() / price);
transaction.lockedForUpdate = true; transaction.lockedForUpdate = true;
this.#transactions.push(transaction); this.#transactions.push(transaction);
this.#updateTransactionsPerPoolCounter(worker.getPool(), 1);
this.#saveTransactions(); this.#saveTransactions();
this.#api.requestBuy(transaction); this.#api.requestBuy(transaction);
@ -425,11 +436,26 @@ export default class TradingBot {
} }
} }
/**
* @param {string} pool
* @param {number} changeValue
*/
#updateTransactionsPerPoolCounter(pool, changeValue) {
if (this.#activeTransactionPerPoolCounter.has(pool)) {
this.#activeTransactionPerPoolCounter.set(pool, Math.max(0, this.#activeTransactionPerPoolCounter.get(pool) + changeValue));
} else {
this.#activeTransactionPerPoolCounter.set(pool, Math.max(0, changeValue));
}
}
#loadTransactions() { #loadTransactions() {
try { try {
this.#transactions = SerializableHelper.load(this.#config.getDataDirectory(), 'transactions.sjson', Transaction); this.#transactions = SerializableHelper.load(this.#config.getDataDirectory(), 'transactions.sjson', Transaction);
this.#transactions = this.#transactions.filter(t => t.phase != TransactionPhase.INITIAL); this.#transactions = this.#transactions.filter(t => t.phase != TransactionPhase.INITIAL);
this.#transactions.forEach(t => t.lockedForUpdate = false); this.#transactions.forEach(t => {
t.lockedForUpdate = false;
this.#updateTransactionsPerPoolCounter(this.#worker.get(t.initiator).getPool(), 1);
});
} catch (e) { } catch (e) {
this.#logger.warn("Bot was unable to load any transactions. Assuming no active transactions existing!", e); this.#logger.warn("Bot was unable to load any transactions. Assuming no active transactions existing!", e);
} }

View File

@ -97,6 +97,16 @@ export default class AggregatedDataPoint {
*/ */
ema5min = 0; ema5min = 0;
/**
* @type {number}
*/
sma1h = 0;
/**
* @type {number}
*/
ema1h = 0;
/** /**
* @type {number[]} * @type {number[]}
*/ */

View File

@ -60,8 +60,10 @@ export default class AssetDataAggregator {
tmpSlot.ema5min = AssetInstrumentCalculator.calculateEMA(this.#perMinuteDataPoints.slice(-1 * Math.min(5, this.#perMinuteDataPoints.length))); tmpSlot.ema5min = AssetInstrumentCalculator.calculateEMA(this.#perMinuteDataPoints.slice(-1 * Math.min(5, this.#perMinuteDataPoints.length)));
tmpSlot.sma15min = AssetInstrumentCalculator.calculateSMA(this.#perMinuteDataPoints.slice(-1 * Math.min(15, this.#perMinuteDataPoints.length))); tmpSlot.sma15min = AssetInstrumentCalculator.calculateSMA(this.#perMinuteDataPoints.slice(-1 * Math.min(15, this.#perMinuteDataPoints.length)));
tmpSlot.ema15min = AssetInstrumentCalculator.calculateEMA(this.#perMinuteDataPoints.slice(-1 * Math.min(15, this.#perMinuteDataPoints.length))); tmpSlot.ema15min = AssetInstrumentCalculator.calculateEMA(this.#perMinuteDataPoints.slice(-1 * Math.min(15, this.#perMinuteDataPoints.length)));
tmpSlot.sma1h = AssetInstrumentCalculator.calculateSMA(this.#perMinuteDataPoints.slice(-1 * Math.min(60, this.#perMinuteDataPoints.length)));
tmpSlot.ema1h = AssetInstrumentCalculator.calculateEMA(this.#perMinuteDataPoints.slice(-1 * Math.min(60, this.#perMinuteDataPoints.length)));
} else { } else {
tmpSlot.sma5min = tmpSlot.ema5min = tmpSlot.sma15min = tmpSlot.ema15min = tmpSlot.avgPrice; tmpSlot.sma5min = tmpSlot.ema5min = tmpSlot.sma15min = tmpSlot.ema15min = tmpSlot.sma1h = tmpSlot.ema1h = tmpSlot.avgPrice;
} }
this.#lastOneMinUpdate = timestamp; this.#lastOneMinUpdate = timestamp;

View File

@ -19,6 +19,11 @@ export default class AbstractWorker extends Serializable {
*/ */
#name = ""; #name = "";
/**
* @type {string} pool name. All workes in same pool shares same balance
*/
#pool = "default";
/** /**
* @type {TradingPair} tradingpair * @type {TradingPair} tradingpair
*/ */
@ -80,6 +85,20 @@ export default class AbstractWorker extends Serializable {
this.#name = name; this.#name = name;
} }
/**
* @returns {string}
*/
getPool() {
return this.#pool;
}
/**
* @param {string} pool
*/
setPool(pool) {
this.#pool = pool;
}
/** /**
* @returns {string} * @returns {string}
*/ */
@ -168,6 +187,7 @@ export default class AbstractWorker extends Serializable {
const obj = JSON.parse(super.toJson()); const obj = JSON.parse(super.toJson());
obj.id = this.#id; obj.id = this.#id;
obj.name = this.#name; obj.name = this.#name;
obj.pool = this.#pool;
obj.tradingPair = SerializableHelper.serialize(this.#tradingpair); obj.tradingPair = SerializableHelper.serialize(this.#tradingpair);
obj.strategy = SerializableHelper.serialize(this.#strategy); obj.strategy = SerializableHelper.serialize(this.#strategy);
@ -187,6 +207,9 @@ export default class AbstractWorker extends Serializable {
worker.#name = obj.name; worker.#name = obj.name;
worker.#tradingpair = SerializableHelper.deserialize(obj.tradingPair); worker.#tradingpair = SerializableHelper.deserialize(obj.tradingPair);
worker.#strategy = SerializableHelper.deserialize(obj.strategy); worker.#strategy = SerializableHelper.deserialize(obj.strategy);
if (obj.pool != null) {
worker.#pool = obj.pool;
}
return worker; return worker;
} }

View File

@ -5,6 +5,7 @@ import WebViewDataProvider from "./WebViewDataProvider.js";
import ConverterFactory from "./converter/ConverterFactory.js"; import ConverterFactory from "./converter/ConverterFactory.js";
import AggregatedDataPointConverter from "./converter/converters/AggregatedDataPointConverter.js"; import AggregatedDataPointConverter from "./converter/converters/AggregatedDataPointConverter.js";
import TransactionConverter from "./converter/converters/TransactionConverter.js"; import TransactionConverter from "./converter/converters/TransactionConverter.js";
import WorkerConverter from "./converter/converters/WorkerConverter.js";
export default class RestClient { export default class RestClient {
@ -78,31 +79,45 @@ export default class RestClient {
}); });
this.#service.get("/asset/:symbol/aggregated", (req, res, next) => { this.#service.get("/asset/:symbol/aggregated", (req, res, next) => {
res.json(this.#getAggregatedAssetData(req.params.symbol, req.query.startTime, req.query.duration)); res.json(this.#getAggregatedAssetData(req.params.symbol, req.query.startTime, req.query.duration, req.query.allowUnfilled));
}); });
this.#service.get("/asset/:symbol/balance", (req, res, next) => { this.#service.get("/asset/:symbol/balance", (req, res, next) => {
res.json(this.#getBalances(req.params.symbol)); res.json(this.#getBalances(req.params.symbol));
}); });
this.#service.get("/worker", (req, res, next) => {
res.json(this.#getWorker());
});
this.#service.get("/worker/:name/attribute/:attr", (req, res, next) => { this.#service.get("/worker/:name/attribute/:attr", (req, res, next) => {
res.json(this.#getWorkerAttribute(req.params.name, req.params.attr)); res.json(this.#getWorkerAttribute(req.params.name, req.params.attr));
}); });
/*this.#service.get("/transactions", (req, res, next) => {
res.json(this.#getAssetOrderBook(req.params.symbol));
});*/
} }
#registerSetters(){ #registerSetters(){
this.#service.get("/asset/:symbol/transaction/:transactionID/sell", (req, res, next) => {
// TODO sell transaction if status still same as before (query parameter: old status)
//res.json(this.#getTransactions(req.params.symbol, req.query.type));
});
this.#service.get("/asset/:symbol/transaction/:transactionID/cancel", (req, res, next) => {
// TODO cancle transaction if status still same as before (query parameter: old status)
//res.json(this.#getTransactions(req.params.symbol, req.query.type));
});
this.#service.get("/asset/:symbol/transaction/:transactionID/delete", (req, res, next) => {
// TODO sell transaction if status still same as before (query parameter: old status)
//res.json(this.#getTransactions(req.params.symbol, req.query.type));
});
} }
#getAggregatedAssetData(asset, starttime, duration){ #getAggregatedAssetData(asset, starttime, duration, allowUnfilled){
const st = starttime != null ? starttime : -1; const st = starttime != null ? starttime : -1;
const d = duration != null ? duration : 3600000; const d = duration != null ? duration : 3600000;
const allowUnfinished= allowUnfilled != null ? allowUnfilled == "true" : false;
const data = this.#dataProvider.getAssetData(asset).getAggregatedData(d, st); const data = this.#dataProvider.getAssetData(asset).getAggregatedData(d, st, allowUnfinished);
const converter = new AggregatedDataPointConverter(); const converter = new AggregatedDataPointConverter();
const result = []; const result = [];
@ -164,6 +179,16 @@ export default class RestClient {
return orderBooks; return orderBooks;
} }
#getWorker(){
const workerConverter = new WorkerConverter();
let result = [];
this.#dataProvider.getWorkers().forEach(w => {
result.push(workerConverter.toRestObject(w));
});
return result;
}
#getWorkerAttribute(name, attributeName){ #getWorkerAttribute(name, attributeName){
let result = null; let result = null;
this.#dataProvider.getWorkers().forEach(w => { this.#dataProvider.getWorkers().forEach(w => {

View File

@ -3,12 +3,14 @@ import OrderBookEntry from "../../apiwrapper/orderbook/OrderBookEntry.js";
import Transaction from "../../apiwrapper/transaction/Transaction.js"; import Transaction from "../../apiwrapper/transaction/Transaction.js";
import TransactionSettings from "../../apiwrapper/transaction/TransactionSettings.js"; import TransactionSettings from "../../apiwrapper/transaction/TransactionSettings.js";
import AggregatedDataPoint from "../../tradingbot/data/asset/AggregatedDataPoint.js"; import AggregatedDataPoint from "../../tradingbot/data/asset/AggregatedDataPoint.js";
import AbstractWorker from "../../tradingbot/worker/AbstractWorker.js";
import AbstractConverter from "./AbstractConverter.js"; import AbstractConverter from "./AbstractConverter.js";
import AggregatedDataPointConverter from "./converters/AggregatedDataPointConverter.js"; import AggregatedDataPointConverter from "./converters/AggregatedDataPointConverter.js";
import OrderBookConverter from "./converters/OrderBookConverter.js"; import OrderBookConverter from "./converters/OrderBookConverter.js";
import OrderBookEntryConverter from "./converters/OrderBookEntryConverter.js"; import OrderBookEntryConverter from "./converters/OrderBookEntryConverter.js";
import TransactionConverter from "./converters/TransactionConverter.js"; import TransactionConverter from "./converters/TransactionConverter.js";
import TransactionSettingsConverter from "./converters/TransactionSettingsConverter.js"; import TransactionSettingsConverter from "./converters/TransactionSettingsConverter.js";
import WorkerConverter from "./converters/WorkerConverter.js";
export default class ConverterFactory { export default class ConverterFactory {
static OBJECT_TYPE_ORDER_BOOK = 'order_book'; static OBJECT_TYPE_ORDER_BOOK = 'order_book';
@ -16,6 +18,7 @@ export default class ConverterFactory {
static OBJECT_TYPE_AGGREGATED_DATA_POINT = 'aggregated_data_point'; static OBJECT_TYPE_AGGREGATED_DATA_POINT = 'aggregated_data_point';
static OBJECT_TYPE_TRANSACTION = 'transaction'; static OBJECT_TYPE_TRANSACTION = 'transaction';
static OBJECT_TYPE_TRANSACTION_SETTINGS = 'transaction_settings'; static OBJECT_TYPE_TRANSACTION_SETTINGS = 'transaction_settings';
static OBJECT_TYPE_ABSTRACT_WORKER = 'abstract_worker';
/** /**
* @param {any} obj * @param {any} obj
@ -40,6 +43,8 @@ export default class ConverterFactory {
return new TransactionConverter(); return new TransactionConverter();
} else if (obj instanceof TransactionSettings) { } else if (obj instanceof TransactionSettings) {
return new TransactionSettingsConverter(); return new TransactionSettingsConverter();
} else if (obj instanceof AbstractWorker) {
return new WorkerConverter();
} }
throw new Error("No converter defined for: " + JSON.stringify(obj)); throw new Error("No converter defined for: " + JSON.stringify(obj));
@ -61,6 +66,8 @@ export default class ConverterFactory {
return new TransactionConverter(); return new TransactionConverter();
case this.OBJECT_TYPE_TRANSACTION_SETTINGS: case this.OBJECT_TYPE_TRANSACTION_SETTINGS:
return new TransactionSettingsConverter(); return new TransactionSettingsConverter();
case this.OBJECT_TYPE_ABSTRACT_WORKER:
return new WorkerConverter();
default: default:
throw new Error("No converter defined for type: " + type); throw new Error("No converter defined for type: " + type);
} }

View File

@ -0,0 +1,32 @@
import AbstractWorker from "../../../tradingbot/worker/AbstractWorker.js";
import AbstractConverter from "../AbstractConverter.js";
import ConverterFactory from "../ConverterFactory.js";
export default class WorkerConverter extends AbstractConverter {
constructor(){
super();
}
/**
* @param {AbstractWorker} obj
* @returns {object}
*/
toRestObject(obj) {
return {
_objectType: ConverterFactory.OBJECT_TYPE_ABSTRACT_WORKER,
id: obj.getId(),
name: obj.getName(),
symbol: obj.getTradingPair().getKey(),
strategy: obj.getStrategy().constructor.name
};
}
/**
* @param {object} obj
* @returns {AbstractWorker}
*/
fromRestObject(obj) {
return null;
}
}