Skip to content

Commit

Permalink
added option to disable balance checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Ekliptor authored and Ekliptor committed Aug 1, 2020
1 parent 271b128 commit 65e309d
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 13 deletions.
1 change: 1 addition & 0 deletions public/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@
"confDesc": {
"exchanges": "Here you have to select the exchange you want to trade on. For arbitrage you must choose 2 exchanges.",
"marginTrading": "Do you want to do margin (leveraged) trading on this exchange? This setting must be enabled for futures trading.",
"checkCoinBalances": "Verify we don't buy/sell more than our portfolio balance has availble (for non-margin trading) to avoid API errors.",
"tradeTotalBtc": "Enter the total amount you want to trade in your base currency (USD when trading USD_BTC, BTC when trading BTC_ETH,...). If you enable margin trading this amount will be leveraged (multiplied).",
"updateIndicatorsOnTrade": "If enabled all technical indicators will be updated on every trade that happens on the exchange. This means indicator values on the latest candle will always change. The default behaviour is to only update indicator values once the candle is complete.",
"flipPosition": "By enabling this WolfBot will trade with 2x \"tradeTotalBtc\" if there already is an open position. This means you can always switch between a long and short short position with a single trade.<br>This only applies to buy an sell signals (close signals will still close the position).",
Expand Down
2 changes: 1 addition & 1 deletion src/Exchanges/Binance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export default class Binance extends AbstractExchange implements ExternalTickerE
this.httpKeepConnectionsAlive = true;
this.dateTimezoneSuffix = "";
this.exchangeLabel = Currency.Exchange.BINANCE;
this.minTradingValue = 0.001; // https://support.binance.com/hc/en-us/articles/115000594711-Trading-Rule
this.minTradingValue = 0.0; // 0.001 // https://support.binance.com/hc/en-us/articles/115000594711-Trading-Rule
this.fee = 0.001; // https://support.binance.com/hc/en-us/articles/115000429332-Fee-Structure-on-Binance
this.maxLeverage = 0.0; // now supports margin // TODO ??
this.currencies = new BinanceCurrencies(this);
Expand Down
26 changes: 23 additions & 3 deletions src/Exchanges/BinanceCcxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import * as utils from "@ekliptor/apputils";
const logger = utils.logger
, nconf = utils.nconf;
import {MarketOrder, Ticker, Trade, TradeHistory, Currency} from "@ekliptor/bit-models";
import {CcxtExchange} from "./CcxtExchange";
import {ExOptions, OpenOrders, OrderParameters} from "./AbstractExchange";
import {CcxtExchange, CcxtOrderParameters} from "./CcxtExchange";
import {ExOptions, ExRequestParams, OpenOrders, OrderParameters} from "./AbstractExchange";
import * as ccxt from "ccxt";
import {OrderResult} from "../structs/OrderResult";

Expand All @@ -12,7 +12,7 @@ export default class BinanceCcxt extends CcxtExchange {
constructor(options: ExOptions) {
super(options);
this.exchangeLabel = Currency.Exchange.BINANCE;
this.minTradingValue = 0.001;
this.minTradingValue = 0.0; // 0.001 // use 0 and hat exchange handle it
this.fee = 0.001;
this.currencies.setSwitchCurrencyPair(true);
let opts = this.getExchangeConfig();
Expand All @@ -30,4 +30,24 @@ export default class BinanceCcxt extends CcxtExchange {
// ################################################################
// ###################### PRIVATE FUNCTIONS #######################

protected verifyTradeRequest(currencyPair: Currency.CurrencyPair, rate: number, amount: number, params: CcxtOrderParameters = {}) {
return new Promise<ExRequestParams>((resolve, reject) => {
if (currencyPair) {
if (this.currencies.getExchangePair(currencyPair) === undefined)
return reject({txt: "Currency pair not supported by this exchange", exchange: this.className, pair: currencyPair, permanent: true});
}
// binance CCXT has the needed precision. wait for API failure on min balance (depending on coin)
//if (amount > 0 && rate * amount < this.minTradingValue)
//return reject({txt: "Value is below the min trading value", exchange: this.className, value: rate*amount, minTradingValue: this.minTradingValue, permanent: true})

let outParams: any = {
dummy: "use-api-client",
orderType: params.matchBestPrice ? "market" : "limit",
pairStr: this.currencies.getExchangePair(currencyPair),
// precision mostly 8 or 6 http://python-binance.readthedocs.io/en/latest/binance.html#binance.client.Client.get_symbol_info
rate: rate
}
resolve(outParams)
})
}
}
9 changes: 6 additions & 3 deletions src/Exchanges/CcxtExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,12 @@ export abstract class CcxtExchange extends AbstractExchange {

public async sell(currencyPair: Currency.CurrencyPair, rate: number, amount: number, params: CcxtOrderParameters = {}): Promise<OrderResult> {
let outParams = await this.verifyTradeRequest(currencyPair, rate, amount, params)
if (this.currencies.isSwitchedCurrencyPair() === true)
//amount /= rate;
amount *= rate;
if (this.currencies.isSwitchedCurrencyPair() === true) {
if (Currency.isFiatCurrency(currencyPair.from) === true)// not needed for binance
amount /= rate;
//amount *= rate;
}

amount = parseFloat(utils.calc.round(amount, 8) + ""); // remove trailing 0
try {
let result = await this.apiClient.createOrder(outParams.pairStr as string, outParams.orderType as any, "sell", amount, outParams.rate as number, params as any);
Expand Down
7 changes: 5 additions & 2 deletions src/Trade/PortfolioTrader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -917,11 +917,14 @@ export abstract class PortfolioTrader extends AbstractTrader {
else
logger.warn("No margin trading portfolio found for exchange %s. Closing with config coin amount")
}
else {
else if (this.config.checkCoinBalances === true) {
let holdingCoinsList = PortfolioTrader.coinBalances.get(exchange.getClassName());
let holdingCoins = holdingCoinsList[coinPair.to]; // always positive
if (holdingCoins)
if (holdingCoins) {
if (holdingCoins > coinAmount) // TODO add config ignoreCoinBalance to always try to sell the config amount?
logger.warn("Can not %s %s > %s %s, reducing amount", trade.toUpperCase(), holdingCoins.toFixed(8), coinAmount.toFixed(8), coinPair.toString());
return Math.min(coinAmount, holdingCoins * maxClosePartialFactor);
}
else if (!holdingCoinsList)
logger.warn("No trading portfolio found for exchange %s. Closing with config coin amount")
}
Expand Down
4 changes: 4 additions & 0 deletions src/Trade/TradeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type TradingMode = "ai" | "lending" | "arbitrage" | "social" | "trading";

export interface ConfigRuntimeUpdate {
marginTrading: boolean;
checkCoinBalances: boolean;
tradeTotalBtc: number;
maxLeverage: number;
tradeDirection: TradeDirection;
Expand All @@ -29,6 +30,7 @@ export class TradeConfig extends AbstractConfig {
public readonly exchangeFeeds: string[] = null; // some of the specified exchanges can be used as read-only (no trades submitted). useful to debug arbitrage
public readonly markets: Currency.CurrencyPair[] = [];
public readonly marginTrading: boolean = true;
public readonly checkCoinBalances: boolean = true; // verify we don't buy/sell more than our portfolio balance has (for non-margin trading) to avoid API errors
public readonly tradeTotalBtc = 0.0; // will be leveraged 2.5 if marginTrading is enabled
public readonly maxLeverage = 0.0; // in AbstractExchange default is 0.0 too
public readonly tradeDirection: TradeDirection = "both";
Expand Down Expand Up @@ -73,6 +75,8 @@ export class TradeConfig extends AbstractConfig {
*/
if (typeof json.marginTrading === "boolean")
this.marginTrading = json.marginTrading;
if (typeof json.checkCoinBalances === "boolean")
this.checkCoinBalances = json.checkCoinBalances;
this.tradeTotalBtc = json.tradeTotalBtc;
if (json.tradeDirection === "up" || json.tradeDirection === "down" || json.tradeDirection === "both")
this.tradeDirection = json.tradeDirection;
Expand Down
1 change: 1 addition & 0 deletions src/WebSocket/ConfigEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,7 @@ export class ConfigEditor extends AppPublisher {
let conf = json.data[i]
let update = {
marginTrading: conf.marginTrading,
checkCoinBalances: conf.checkCoinBalances,
tradeTotalBtc: conf.tradeTotalBtc,
maxLeverage: conf.maxLeverage ? parseFloat(conf.maxLeverage) : 1.0,
tradeDirection: conf.tradeDirection,
Expand Down
10 changes: 6 additions & 4 deletions tests/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,15 @@ let testBinance = () => {

//let pair =[Currency.Currency.BTC, Currency.Currency.ETH]
let pair = new Currency.CurrencyPair(Currency.Currency.USDT, Currency.Currency.BTC)
//let pair = new Currency.CurrencyPair(Currency.Currency.BTC, Currency.Currency.ETH)
binance.subscribeToMarkets([pair])

binance.buy(pair, 8000.0, 0.1).then((balances) => {
//binance.buy(pair, 8000.0, 0.1).then((balances) => {
//binance.marginBuy(pair, 0.0091495725, 1.0929472387917578, {}).then((balances) => {
//binance.getOpenOrders(pair).then((balances) => {
//binance.importHistory(pair, new Date(Date.now()-2*utils.constants.HOUR_IN_SECONDS*1000), new Date()).then((balances) => {
//binance.sell(pair, 0.00000623, 350).then((balances) => {
//binance.sell(pair, 0.0315, 5).then((balances) => {
binance.sell(pair, 11500.234982347, 1000).then((balances) => {
//binance.getOpenOrders(pair).then((balances) => {
//binance.moveOrder(pair, 25959783, 0.00000723, 360, params).then((balances) => {
//binance.getExternalTicker(["USD_BTC"]).then((balances) => {
Expand Down Expand Up @@ -431,12 +433,12 @@ Controller.loadServerConfig(() => {
//testBitfinex()
//testPolo();
//testBittrex();
//testBinance();
testBinance();
//testBitmex();
//testBitmexLiquidations();
//testDeribit();
//testBx();
testCcxt();
//testCcxt();
//testPaetio();
//updateHistory();
})
Expand Down

0 comments on commit 65e309d

Please sign in to comment.