From 93b729a5d559ea9bf2b1d93840347516431fe3da Mon Sep 17 00:00:00 2001 From: gcarq Date: Fri, 13 Oct 2017 21:09:55 +0200 Subject: [PATCH] replace get_ticker with get_orderbook --- freqtrade/exchange/__init__.py | 6 +++--- freqtrade/exchange/bittrex.py | 11 +++++------ freqtrade/exchange/interface.py | 24 ++++++++++++++++++------ freqtrade/main.py | 15 ++++++++------- freqtrade/rpc/telegram.py | 6 +++--- 5 files changed, 37 insertions(+), 25 deletions(-) diff --git a/freqtrade/exchange/__init__.py b/freqtrade/exchange/__init__.py index 77a2d4b84..17e9649af 100644 --- a/freqtrade/exchange/__init__.py +++ b/freqtrade/exchange/__init__.py @@ -1,6 +1,6 @@ import enum import logging -from typing import List +from typing import List, Optional, Dict import arrow @@ -85,8 +85,8 @@ def get_balance(currency: str) -> float: return EXCHANGE.get_balance(currency) -def get_ticker(pair: str) -> dict: - return EXCHANGE.get_ticker(pair) +def get_orderbook(pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]: + return EXCHANGE.get_orderbook(pair, top_most) def get_ticker_history(pair: str, minimum_date: arrow.Arrow): diff --git a/freqtrade/exchange/bittrex.py b/freqtrade/exchange/bittrex.py index ebd87cc18..6519f7ff5 100644 --- a/freqtrade/exchange/bittrex.py +++ b/freqtrade/exchange/bittrex.py @@ -1,5 +1,5 @@ import logging -from typing import List, Optional +from typing import List, Optional, Dict import arrow from bittrex.bittrex import Bittrex as _Bittrex, API_V2_0 @@ -56,14 +56,13 @@ class Bittrex(Exchange): raise RuntimeError('{}: {}'.format(self.name.upper(), data['message'])) return float(data['result']['Balance'] or 0.0) - def get_ticker(self, pair: str) -> dict: - data = _API.get_ticker(pair.replace('_', '-')) + def get_orderbook(self, pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]: + data = _API.get_orderbook(pair.replace('_', '-')) if not data['success']: raise RuntimeError('{}: {}'.format(self.name.upper(), data['message'])) return { - 'bid': float(data['result']['Bid']), - 'ask': float(data['result']['Ask']), - 'last': float(data['result']['Last']), + 'bid': data['result']['buy'][:top_most], + 'ask': data['result']['sell'][:top_most], } def get_ticker_history(self, pair: str, minimum_date: Optional[arrow.Arrow] = None): diff --git a/freqtrade/exchange/interface.py b/freqtrade/exchange/interface.py index 114ac9a6f..67c910504 100644 --- a/freqtrade/exchange/interface.py +++ b/freqtrade/exchange/interface.py @@ -1,5 +1,5 @@ from abc import ABC, abstractmethod -from typing import List, Optional +from typing import List, Optional, Dict import arrow @@ -50,14 +50,26 @@ class Exchange(ABC): """ @abstractmethod - def get_ticker(self, pair: str) -> dict: + def get_orderbook(self, pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]: """ - Gets ticker for given pair. + Gets orderbook for given pair. :param pair: Pair as str, format: BTC_ETC + :param top_most: only return n top_most bids/sells (optional) :return: dict, format: { - 'bid': float, - 'ask': float, - 'last': float + 'bid': [ + { + 'Quantity': float, + 'Rate': float, + }, + ... + ], + 'ask': [ + { + 'Quantity': float, + 'Rate': float, + }, + ... + ] } """ diff --git a/freqtrade/main.py b/freqtrade/main.py index ce933fe44..2e8163b62 100755 --- a/freqtrade/main.py +++ b/freqtrade/main.py @@ -5,7 +5,7 @@ import logging import time import traceback from datetime import datetime -from typing import Dict, Optional +from typing import Dict, Optional, List from jsonschema import validate @@ -134,7 +134,7 @@ def handle_trade(trade: Trade) -> None: logger.debug('Handling open trade %s ...', trade) - current_rate = exchange.get_ticker(trade.pair)['bid'] + current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate'] if should_sell(trade, current_rate, datetime.utcnow()): execute_sell(trade, current_rate) return @@ -143,12 +143,13 @@ def handle_trade(trade: Trade) -> None: logger.exception('Unable to handle open order') -def get_target_bid(ticker: Dict[str, float]) -> float: +def get_target_bid(ticker: Dict[str, List[Dict]]) -> float: """ Calculates bid target between current ask price and last price """ - if ticker['ask'] < ticker['last']: - return ticker['ask'] + # TODO: refactor this + ask = ticker['ask'][0]['Rate'] + bid = ticker['bid'][0]['Rate'] balance = _CONF['bid_strategy']['ask_last_balance'] - return ticker['ask'] + balance * (ticker['last'] - ticker['ask']) + return ask + balance * (bid - ask) def create_trade(stake_amount: float) -> Optional[Trade]: @@ -181,7 +182,7 @@ def create_trade(stake_amount: float) -> Optional[Trade]: else: return None - open_rate = get_target_bid(exchange.get_ticker(pair)) + open_rate = get_target_bid(exchange.get_orderbook(pair, top_most=1)) amount = stake_amount / open_rate order_id = exchange.buy(pair, open_rate, amount) diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index 5312125ed..a09e6087e 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -99,7 +99,7 @@ def _status(bot: Bot, update: Update) -> None: else: for trade in trades: # calculate profit and send message to user - current_rate = exchange.get_ticker(trade.pair)['bid'] + current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate'] current_profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate) orders = exchange.get_open_orders(trade.pair) orders = [o for o in orders if o['id'] == trade.open_order_id] @@ -156,7 +156,7 @@ def _profit(bot: Bot, update: Update) -> None: profit = trade.close_profit else: # Get current rate - current_rate = exchange.get_ticker(trade.pair)['bid'] + current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate'] profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate) profit_amounts.append((profit / 100) * trade.stake_amount) @@ -250,7 +250,7 @@ def _forcesell(bot: Bot, update: Update) -> None: send_msg('There is no open trade with ID: `{}`'.format(trade_id)) return # Get current rate - current_rate = exchange.get_ticker(trade.pair)['bid'] + current_rate = exchange.get_orderbook(trade.pair, top_most=1)['bid'][0]['Rate'] # Get available balance currency = trade.pair.split('_')[1] balance = exchange.get_balance(currency)