replace get_ticker with get_orderbook

This commit is contained in:
gcarq 2017-10-13 21:09:55 +02:00
parent b3ed0151f0
commit 93b729a5d5
5 changed files with 37 additions and 25 deletions

View File

@ -1,6 +1,6 @@
import enum import enum
import logging import logging
from typing import List from typing import List, Optional, Dict
import arrow import arrow
@ -85,8 +85,8 @@ def get_balance(currency: str) -> float:
return EXCHANGE.get_balance(currency) return EXCHANGE.get_balance(currency)
def get_ticker(pair: str) -> dict: def get_orderbook(pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]:
return EXCHANGE.get_ticker(pair) return EXCHANGE.get_orderbook(pair, top_most)
def get_ticker_history(pair: str, minimum_date: arrow.Arrow): def get_ticker_history(pair: str, minimum_date: arrow.Arrow):

View File

@ -1,5 +1,5 @@
import logging import logging
from typing import List, Optional from typing import List, Optional, Dict
import arrow import arrow
from bittrex.bittrex import Bittrex as _Bittrex, API_V2_0 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'])) raise RuntimeError('{}: {}'.format(self.name.upper(), data['message']))
return float(data['result']['Balance'] or 0.0) return float(data['result']['Balance'] or 0.0)
def get_ticker(self, pair: str) -> dict: def get_orderbook(self, pair: str, top_most: Optional[int] = None) -> Dict[str, List[Dict]]:
data = _API.get_ticker(pair.replace('_', '-')) data = _API.get_orderbook(pair.replace('_', '-'))
if not data['success']: if not data['success']:
raise RuntimeError('{}: {}'.format(self.name.upper(), data['message'])) raise RuntimeError('{}: {}'.format(self.name.upper(), data['message']))
return { return {
'bid': float(data['result']['Bid']), 'bid': data['result']['buy'][:top_most],
'ask': float(data['result']['Ask']), 'ask': data['result']['sell'][:top_most],
'last': float(data['result']['Last']),
} }
def get_ticker_history(self, pair: str, minimum_date: Optional[arrow.Arrow] = None): def get_ticker_history(self, pair: str, minimum_date: Optional[arrow.Arrow] = None):

View File

@ -1,5 +1,5 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from typing import List, Optional from typing import List, Optional, Dict
import arrow import arrow
@ -50,14 +50,26 @@ class Exchange(ABC):
""" """
@abstractmethod @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 pair: Pair as str, format: BTC_ETC
:param top_most: only return n top_most bids/sells (optional)
:return: dict, format: { :return: dict, format: {
'bid': float, 'bid': [
'ask': float, {
'last': float 'Quantity': float,
'Rate': float,
},
...
],
'ask': [
{
'Quantity': float,
'Rate': float,
},
...
]
} }
""" """

View File

@ -5,7 +5,7 @@ import logging
import time import time
import traceback import traceback
from datetime import datetime from datetime import datetime
from typing import Dict, Optional from typing import Dict, Optional, List
from jsonschema import validate from jsonschema import validate
@ -134,7 +134,7 @@ def handle_trade(trade: Trade) -> None:
logger.debug('Handling open trade %s ...', trade) 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()): if should_sell(trade, current_rate, datetime.utcnow()):
execute_sell(trade, current_rate) execute_sell(trade, current_rate)
return return
@ -143,12 +143,13 @@ def handle_trade(trade: Trade) -> None:
logger.exception('Unable to handle open order') 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 """ """ Calculates bid target between current ask price and last price """
if ticker['ask'] < ticker['last']: # TODO: refactor this
return ticker['ask'] ask = ticker['ask'][0]['Rate']
bid = ticker['bid'][0]['Rate']
balance = _CONF['bid_strategy']['ask_last_balance'] 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]: def create_trade(stake_amount: float) -> Optional[Trade]:
@ -181,7 +182,7 @@ def create_trade(stake_amount: float) -> Optional[Trade]:
else: else:
return None 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 amount = stake_amount / open_rate
order_id = exchange.buy(pair, open_rate, amount) order_id = exchange.buy(pair, open_rate, amount)

View File

@ -99,7 +99,7 @@ def _status(bot: Bot, update: Update) -> None:
else: else:
for trade in trades: for trade in trades:
# calculate profit and send message to user # 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) current_profit = 100 * ((current_rate - trade.open_rate) / trade.open_rate)
orders = exchange.get_open_orders(trade.pair) orders = exchange.get_open_orders(trade.pair)
orders = [o for o in orders if o['id'] == trade.open_order_id] 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 profit = trade.close_profit
else: else:
# Get current rate # 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 = 100 * ((current_rate - trade.open_rate) / trade.open_rate)
profit_amounts.append((profit / 100) * trade.stake_amount) 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)) send_msg('There is no open trade with ID: `{}`'.format(trade_id))
return return
# Get current rate # 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 # Get available balance
currency = trade.pair.split('_')[1] currency = trade.pair.split('_')[1]
balance = exchange.get_balance(currency) balance = exchange.get_balance(currency)