Skip to content

Commit

Permalink
Fix: changed property name
Browse files Browse the repository at this point in the history
  • Loading branch information
edeng23 committed May 5, 2023
1 parent 29ce7a1 commit 3eaf949
Show file tree
Hide file tree
Showing 16 changed files with 388 additions and 120 deletions.
4 changes: 3 additions & 1 deletion .pre-commit-hooks/sort-coins-file.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
def sort():
in_contents = SUPPORTED_COIN_LIST.read_text()
out_contents = ""
out_contents += "\n".join(sorted([line.upper() for line in in_contents.splitlines()]))
out_contents += "\n".join(
sorted([line.upper() for line in in_contents.splitlines()])
)
out_contents += "\n"
if in_contents != out_contents:
SUPPORTED_COIN_LIST.write_text(out_contents)
Expand Down
4 changes: 3 additions & 1 deletion backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
print("TIME:", manager.datetime)
print("BALANCES:", manager.balances)
print("BTC VALUE:", btc_value, f"({btc_diff}%)")
print(f"{manager.config.BRIDGE.symbol} VALUE:", bridge_value, f"({bridge_diff}%)")
print(
f"{manager.config.BRIDGE.symbol} VALUE:", bridge_value, f"({bridge_diff}%)"
)
print("------")
19 changes: 15 additions & 4 deletions binance_trade_bot/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ def filter_period(query, model): # pylint: disable=inconsistent-return-statemen
def value_history(coin: str = None):
session: Session
with db.db_session() as session:
query = session.query(CoinValue).order_by(CoinValue.coin_id.asc(), CoinValue.datetime.asc())
query = session.query(CoinValue).order_by(
CoinValue.coin_id.asc(), CoinValue.datetime.asc()
)

query = filter_period(query, CoinValue)

Expand All @@ -59,7 +61,12 @@ def value_history(coin: str = None):
return jsonify([entry.info() for entry in values])

coin_values = groupby(query.all(), key=lambda cv: cv.coin)
return jsonify({coin.symbol: [entry.info() for entry in history] for coin, history in coin_values})
return jsonify(
{
coin.symbol: [entry.info() for entry in history]
for coin, history in coin_values
}
)


@app.route("/api/total_value_history")
Expand All @@ -75,7 +82,9 @@ def total_value_history():
query = filter_period(query, CoinValue)

total_values: List[Tuple[datetime, float, float]] = query.all()
return jsonify([{"datetime": tv[0], "btc": tv[1], "usd": tv[2]} for tv in total_values])
return jsonify(
[{"datetime": tv[0], "btc": tv[1], "usd": tv[2]} for tv in total_values]
)


@app.route("/api/trade_history")
Expand Down Expand Up @@ -133,7 +142,9 @@ def coins():
with db.db_session() as session:
_current_coin = session.merge(db.get_current_coin())
_coins: List[Coin] = session.query(Coin).all()
return jsonify([{**coin.info(), "is_current": coin == _current_coin} for coin in _coins])
return jsonify(
[{**coin.info(), "is_current": coin == _current_coin} for coin in _coins]
)


@app.route("/api/pairs")
Expand Down
72 changes: 56 additions & 16 deletions binance_trade_bot/auto_trader.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@


class AutoTrader:
def __init__(self, binance_manager: BinanceAPIManager, database: Database, logger: Logger, config: Config):
def __init__(
self,
binance_manager: BinanceAPIManager,
database: Database,
logger: Logger,
config: Config,
):
self.manager = binance_manager
self.db = database
self.logger = logger
Expand All @@ -26,7 +32,9 @@ def transaction_through_bridge(self, pair: Pair):
"""
can_sell = False
balance = self.manager.get_currency_balance(pair.from_coin.symbol)
from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)
from_coin_price = self.manager.get_ticker_price(
pair.from_coin + self.config.BRIDGE
)

if balance and balance * from_coin_price > self.manager.get_min_notional(
pair.from_coin.symbol, self.config.BRIDGE.symbol
Expand All @@ -35,7 +43,10 @@ def transaction_through_bridge(self, pair: Pair):
else:
self.logger.info("Skipping sell")

if can_sell and self.manager.sell_alt(pair.from_coin, self.config.BRIDGE) is None:
if (
can_sell
and self.manager.sell_alt(pair.from_coin, self.config.BRIDGE) is None
):
self.logger.info("Couldn't sell, going back to scouting mode...")
return None

Expand All @@ -54,17 +65,25 @@ def update_trade_threshold(self, coin: Coin, coin_price: float):
"""

if coin_price is None:
self.logger.info("Skipping update... current coin {} not found".format(coin + self.config.BRIDGE))
self.logger.info(
"Skipping update... current coin {} not found".format(
coin + self.config.BRIDGE
)
)
return

session: Session
with self.db.db_session() as session:
for pair in session.query(Pair).filter(Pair.to_coin == coin):
from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)
from_coin_price = self.manager.get_ticker_price(
pair.from_coin + self.config.BRIDGE
)

if from_coin_price is None:
self.logger.info(
"Skipping update for coin {} not found".format(pair.from_coin + self.config.BRIDGE)
"Skipping update for coin {} not found".format(
pair.from_coin + self.config.BRIDGE
)
)
continue

Expand All @@ -81,17 +100,25 @@ def initialize_trade_thresholds(self):
continue
self.logger.info(f"Initializing {pair.from_coin} vs {pair.to_coin}")

from_coin_price = self.manager.get_ticker_price(pair.from_coin + self.config.BRIDGE)
from_coin_price = self.manager.get_ticker_price(
pair.from_coin + self.config.BRIDGE
)
if from_coin_price is None:
self.logger.info(
"Skipping initializing {}, symbol not found".format(pair.from_coin + self.config.BRIDGE)
"Skipping initializing {}, symbol not found".format(
pair.from_coin + self.config.BRIDGE
)
)
continue

to_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE)
to_coin_price = self.manager.get_ticker_price(
pair.to_coin + self.config.BRIDGE
)
if to_coin_price is None:
self.logger.info(
"Skipping initializing {}, symbol not found".format(pair.to_coin + self.config.BRIDGE)
"Skipping initializing {}, symbol not found".format(
pair.to_coin + self.config.BRIDGE
)
)
continue

Expand All @@ -110,11 +137,15 @@ def _get_ratios(self, coin: Coin, coin_price):
ratio_dict: Dict[Pair, float] = {}

for pair in self.db.get_pairs_from(coin):
optional_coin_price = self.manager.get_ticker_price(pair.to_coin + self.config.BRIDGE)
optional_coin_price = self.manager.get_ticker_price(
pair.to_coin + self.config.BRIDGE
)

if optional_coin_price is None:
self.logger.info(
"Skipping scouting... optional coin {} not found".format(pair.to_coin + self.config.BRIDGE)
"Skipping scouting... optional coin {} not found".format(
pair.to_coin + self.config.BRIDGE
)
)
continue

Expand All @@ -130,11 +161,16 @@ def _get_ratios(self, coin: Coin, coin_price):

if self.config.USE_MARGIN == "yes":
ratio_dict[pair] = (
(1 - transaction_fee) * coin_opt_coin_ratio / pair.ratio - 1 - self.config.SCOUT_MARGIN / 100
(1 - transaction_fee) * coin_opt_coin_ratio / pair.ratio
- 1
- self.config.SCOUT_MARGIN / 100
)
else:
ratio_dict[pair] = (
coin_opt_coin_ratio - transaction_fee * self.config.SCOUT_MULTIPLIER * coin_opt_coin_ratio
coin_opt_coin_ratio
- transaction_fee
* self.config.SCOUT_MULTIPLIER
* coin_opt_coin_ratio
) - pair.ratio
return ratio_dict

Expand All @@ -160,15 +196,19 @@ def bridge_scout(self):
bridge_balance = self.manager.get_currency_balance(self.config.BRIDGE.symbol)

for coin in self.db.get_coins():
current_coin_price = self.manager.get_ticker_price(coin + self.config.BRIDGE)
current_coin_price = self.manager.get_ticker_price(
coin + self.config.BRIDGE
)

if current_coin_price is None:
continue

ratio_dict = self._get_ratios(coin, current_coin_price)
if not any(v > 0 for v in ratio_dict.values()):
# There will only be one coin where all the ratios are negative. When we find it, buy it if we can
if bridge_balance > self.manager.get_min_notional(coin.symbol, self.config.BRIDGE.symbol):
if bridge_balance > self.manager.get_min_notional(
coin.symbol, self.config.BRIDGE.symbol
):
self.logger.info(f"Will be purchasing {coin} using bridge coin")
self.manager.buy_alt(coin, self.config.BRIDGE)
return coin
Expand Down
42 changes: 30 additions & 12 deletions binance_trade_bot/backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,15 @@ def get_ticker_price(self, ticker_symbol: str):
if end_date > datetime.now():
end_date = datetime.now()
end_date = end_date.strftime("%d %b %Y %H:%M:%S")
self.logger.info(f"Fetching prices for {ticker_symbol} between {self.datetime} and {end_date}")
self.logger.info(
f"Fetching prices for {ticker_symbol} between {self.datetime} and {end_date}"
)
for result in self.binance_client.get_historical_klines(
ticker_symbol, "1m", target_date, end_date, limit=1000
):
date = datetime.utcfromtimestamp(result[0] / 1000).strftime("%d %b %Y %H:%M:%S")
date = datetime.utcfromtimestamp(result[0] / 1000).strftime(
"%d %b %Y %H:%M:%S"
)
price = float(result[1])
cache[f"{ticker_symbol} - {date}"] = price
cache.commit()
Expand All @@ -75,18 +79,24 @@ def buy_alt(self, origin_coin: Coin, target_coin: Coin):
target_balance = self.get_currency_balance(target_symbol)
from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)

order_quantity = self._buy_quantity(origin_symbol, target_symbol, target_balance, from_coin_price)
order_quantity = self._buy_quantity(
origin_symbol, target_symbol, target_balance, from_coin_price
)
target_quantity = order_quantity * from_coin_price
self.balances[target_symbol] -= target_quantity
self.balances[origin_symbol] = self.balances.get(origin_symbol, 0) + order_quantity * (
1 - self.get_fee(origin_coin, target_coin, False)
)
self.balances[origin_symbol] = self.balances.get(
origin_symbol, 0
) + order_quantity * (1 - self.get_fee(origin_coin, target_coin, False))
self.logger.info(
f"Bought {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: "
f"{self.balances[target_symbol]}"
)

event = defaultdict(lambda: None, order_price=from_coin_price, cumulative_quote_asset_transacted_quantity=0)
event = defaultdict(
lambda: None,
order_price=from_coin_price,
cumulative_quote_asset_transacted_quantity=0,
)

return BinanceOrder(event)

Expand All @@ -97,11 +107,13 @@ def sell_alt(self, origin_coin: Coin, target_coin: Coin):
origin_balance = self.get_currency_balance(origin_symbol)
from_coin_price = self.get_ticker_price(origin_symbol + target_symbol)

order_quantity = self._sell_quantity(origin_symbol, target_symbol, origin_balance)
target_quantity = order_quantity * from_coin_price
self.balances[target_symbol] = self.balances.get(target_symbol, 0) + target_quantity * (
1 - self.get_fee(origin_coin, target_coin, True)
order_quantity = self._sell_quantity(
origin_symbol, target_symbol, origin_balance
)
target_quantity = order_quantity * from_coin_price
self.balances[target_symbol] = self.balances.get(
target_symbol, 0
) + target_quantity * (1 - self.get_fee(origin_coin, target_coin, True))
self.balances[origin_symbol] -= order_quantity
self.logger.info(
f"Sold {origin_symbol}, balance now: {self.balances[origin_symbol]} - bridge: "
Expand Down Expand Up @@ -132,7 +144,13 @@ class MockDatabase(Database):
def __init__(self, logger: Logger, config: Config):
super().__init__(logger, config, "sqlite:///")

def log_scout(self, pair: Pair, target_ratio: float, current_coin_price: float, other_coin_price: float):
def log_scout(
self,
pair: Pair,
target_ratio: float,
current_coin_price: float,
other_coin_price: float,
):
pass


Expand Down
Loading

0 comments on commit 3eaf949

Please sign in to comment.