Skip to content
This repository was archived by the owner on May 8, 2021. It is now read-only.

Commit 329821e

Browse files
commit
1 parent 96648ba commit 329821e

16 files changed

+144
-79
lines changed

libkloudtrader/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
"""Init Libkloudtrader"""
22

33
name = "libkloudtrader"
4-
__version__ = "1.0.0"
4+
__version__ = "1.0.0"
5+
6+
import logging
7+
logger = logging.getLogger(__name__)

libkloudtrader/algorithm.py

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
11
from typing import Any
22
import random
33
import time
4-
import logging
54
import numpy as np
65
import pandas as pd
76
import libkloudtrader.stocks as stocks
8-
from .exceptions import InvalidAlgorithmMode, EmptySymbolBucket, InvalidDataFeedType
7+
from libkloudtrader.exceptions import InvalidAlgorithmMode, EmptySymbolBucket, InvalidDataFeedType
98
from libkloudtrader.enumerables import Data_Types
109
import libkloudtrader.processing as processing
10+
from libkloudtrader.logs import init_logger
1111

12-
logger = logging.getLogger('narwhal')
13-
logging.basicConfig(format='%(asctime)s %(module)s %(levelname)s: %(message)s',
14-
datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.INFO)
15-
12+
logger = init_logger(__name__)
1613

1714
def backtest(symbol: str,
1815
strategy: str,
@@ -44,37 +41,43 @@ def backtest(symbol: str,
4441

4542
def live_trade(strategy_name: str,
4643
symbol_bucket: list,
47-
data_feed_type:str,
44+
data_feed_type: str,
4845
states: list = ['open'],
49-
batch_size:int=1000,feed_delay:float=0.0,fake_feed:bool=False):
46+
batch_size: int = 1000,
47+
feed_delay: float = 0.0,
48+
fake_feed: bool = False):
5049
try:
51-
logging.info("{} is now entering the live markets. All the Best. 👍🏼".format(
50+
logger.info("{} is now entering the live markets. 📈\n".format(
5251
strategy_name.__name__))
5352
if isinstance(symbol_bucket, list):
5453
symbol_bucket = np.array(symbol_bucket)
5554
elif type(symbol_bucket) not in (numpy.ndarray, list):
5655
raise TypeError('Symbol bucket must be a list or numpy array')
57-
if data_feed_type not in ('CRYPTO_live_feed','US_STOCKS_live_feed','CRYPTO_live_feed_level2'):
58-
raise InvalidDataFeedType('This Data Feed is not available for live trading. Please use libkloudtrader.algorithm.backtest() for backtesting or using hisotrical data.')
59-
if data_feed_type in ("CRYPTO_live_feed",'CRYPTO_live_feed_level2'):
60-
feed_delay=2
61-
data_feed=Data_Types[data_feed_type].value
56+
if data_feed_type not in ('CRYPTO_live_feed', 'US_STOCKS_live_feed',
57+
'CRYPTO_live_feed_level2'):
58+
raise InvalidDataFeedType(
59+
'This Data Feed is not available for live trading. Please use libkloudtrader.algorithm.backtest() for backtesting or using hisotrical data.'
60+
)
61+
if data_feed_type in ("CRYPTO_live_feed", 'CRYPTO_live_feed_level2'):
62+
feed_delay = 2
63+
data_feed = Data_Types[data_feed_type].value
6264
while stocks.intraday_status()['state'] in states:
6365
batch = processing.Buffer(batch_size, dtype=object)
6466
while len(batch) < batch_size:
6567
for symbol in symbol_bucket:
66-
batch.append(data_feed(symbol,fake_feed=fake_feed))
68+
batch.append(data_feed(symbol, fake_feed=fake_feed))
6769
data_batch = pd.DataFrame(batch)
68-
locals()['strategy_name'](
69-
data_batch)
70-
if len(batch)==batch_size:
70+
locals()['strategy_name'](data_batch)
71+
if len(batch) == batch_size:
7172
batch.popleft()
7273
time.sleep(feed_delay)
7374
except (KeyboardInterrupt, SystemExit):
7475
print('\n')
75-
logging.critical('User stopped the algorithm')
76+
logger.critical('User stopped the algorithm')
7677
except Exception as exception:
77-
logging.error('Oops! Something went wrong while Narwhal was taking your algorithm to live markets. ⚠️')
78-
raise exception
78+
logger.critical('Exiting {}...'.format(strategy_name.__name__))
79+
logger.warning(
80+
'Oops! Something went wrong while your algorithm was being deployed to live markets. ⚠️'
81+
)
82+
logger.error(exception)
7983
exit()
80-

libkloudtrader/crypto.py

Lines changed: 46 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -735,34 +735,51 @@ def cancel_order(order_id: str,
735735

736736

737737
'''Functions not in documentation'''
738-
def incoming_tick_data_handler(symbol: str, number_of_data_points:int=1,fake_feed:bool=False):
739-
latest_orderbook_entry=order_book(symbol,number_of_data_points=1)
740-
latest_trades=trades(symbol, number_of_data_points=1)
741-
latest_orderbook_entry_dict={}
742-
latest_orderbook_entry_dict['symbol']=symbol
743-
latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][0] if len (latest_orderbook_entry['asks']) > 0 else None
744-
latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][1] if len (latest_orderbook_entry['asks']) > 0 else None
745-
latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][0] if len (latest_orderbook_entry['bids']) > 0 else None
746-
latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][1] if len (latest_orderbook_entry['bids']) > 0 else None
747-
latest_orderbook_entry_dict['quotedate']=latest_orderbook_entry['datetime']
748-
latest_orderbook_entry_dict['nonce']=latest_orderbook_entry['nonce']
749-
latest_orderbook_entry_dict['price']=latest_trades[0]['price']
750-
latest_orderbook_entry_dict['tradesize']=latest_trades[0]['amount']
751-
latest_orderbook_entry_dict['tradedate']=latest_trades[0]['datetime']
738+
739+
740+
def incoming_tick_data_handler(symbol: str,
741+
number_of_data_points: int = 1,
742+
fake_feed: bool = False):
743+
latest_orderbook_entry = order_book(symbol, number_of_data_points=1)
744+
latest_trades = trades(symbol, number_of_data_points=1)
745+
latest_orderbook_entry_dict = {}
746+
latest_orderbook_entry_dict['symbol'] = symbol
747+
latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][
748+
0] if len(latest_orderbook_entry['asks']) > 0 else None
749+
latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][
750+
1] if len(latest_orderbook_entry['asks']) > 0 else None
751+
latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][
752+
0] if len(latest_orderbook_entry['bids']) > 0 else None
753+
latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][
754+
1] if len(latest_orderbook_entry['bids']) > 0 else None
755+
latest_orderbook_entry_dict['quotedate'] = latest_orderbook_entry[
756+
'datetime']
757+
latest_orderbook_entry_dict['nonce'] = latest_orderbook_entry['nonce']
758+
latest_orderbook_entry_dict['price'] = latest_trades[0]['price']
759+
latest_orderbook_entry_dict['tradesize'] = latest_trades[0]['amount']
760+
latest_orderbook_entry_dict['tradedate'] = latest_trades[0]['datetime']
752761
return latest_orderbook_entry_dict
753762

754-
def incoming_tick_data_handler_level2(symbol: str, number_of_data_points:int=1,fake_feed:bool=False):
755-
latest_orderbook_entry=L2_order_book(symbol,number_of_data_points=1)
756-
latest_trades=trades(symbol, number_of_data_points=1)
757-
latest_orderbook_entry_dict={}
758-
latest_orderbook_entry_dict['symbol']=symbol
759-
latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][0] if len (latest_orderbook_entry['asks']) > 0 else None
760-
latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][1] if len (latest_orderbook_entry['asks']) > 0 else None
761-
latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][0] if len (latest_orderbook_entry['bids']) > 0 else None
762-
latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][1] if len (latest_orderbook_entry['bids']) > 0 else None
763-
latest_orderbook_entry_dict['quotedate']=latest_orderbook_entry['datetime']
764-
latest_orderbook_entry_dict['nonce']=latest_orderbook_entry['nonce']
765-
latest_orderbook_entry_dict['price']=latest_trades[0]['price']
766-
latest_orderbook_entry_dict['tradesize']=latest_trades[0]['amount']
767-
latest_orderbook_entry_dict['tradedate']=latest_trades[0]['datetime']
768-
return latest_orderbook_entry_dict
763+
764+
def incoming_tick_data_handler_level2(symbol: str,
765+
number_of_data_points: int = 1,
766+
fake_feed: bool = False):
767+
latest_orderbook_entry = L2_order_book(symbol, number_of_data_points=1)
768+
latest_trades = trades(symbol, number_of_data_points=1)
769+
latest_orderbook_entry_dict = {}
770+
latest_orderbook_entry_dict['symbol'] = symbol
771+
latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][
772+
0] if len(latest_orderbook_entry['asks']) > 0 else None
773+
latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][
774+
1] if len(latest_orderbook_entry['asks']) > 0 else None
775+
latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][
776+
0] if len(latest_orderbook_entry['bids']) > 0 else None
777+
latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][
778+
1] if len(latest_orderbook_entry['bids']) > 0 else None
779+
latest_orderbook_entry_dict['quotedate'] = latest_orderbook_entry[
780+
'datetime']
781+
latest_orderbook_entry_dict['nonce'] = latest_orderbook_entry['nonce']
782+
latest_orderbook_entry_dict['price'] = latest_trades[0]['price']
783+
latest_orderbook_entry_dict['tradesize'] = latest_trades[0]['amount']
784+
latest_orderbook_entry_dict['tradedate'] = latest_trades[0]['datetime']
785+
return latest_orderbook_entry_dict

libkloudtrader/enumerables.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ class Data_Types(Enum):
99
'''Data Types of backtesting and live trading'''
1010
US_STOCKS_daily = partial(stocks.ohlcv)
1111
US_STOCKS_live_feed = partial(stocks.incoming_tick_data_handler)
12-
CRYPTO_live_feed=partial(crypto.incoming_tick_data_handler)
13-
CRYPTO_live_feed_level2=partial(crypto.incoming_tick_data_handler_level2)
12+
CRYPTO_live_feed = partial(crypto.incoming_tick_data_handler)
13+
CRYPTO_live_feed_level2 = partial(crypto.incoming_tick_data_handler_level2)

libkloudtrader/exceptions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class EmptySymbolBucket(Exception):
3232
'''Excption raised if symbol bucket is empty'''
3333
pass
3434

35+
3536
class InvalidDataFeedType(Exception):
3637
'''Exception raised if user asks for invalid data feed'''
37-
pass
38+
pass

libkloudtrader/logs.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import logging
2+
import coloredlogs
3+
4+
coloredlogs.DEFAULT_FIELD_STYLES = {'asctime': {'color': 'green'}}
5+
coloredlogs.DEFAULT_LEVEL_STYLES = {
6+
'critical': {
7+
'color': 'red'
8+
},
9+
'debug': {
10+
'color': 'white'
11+
},
12+
'error': {
13+
'color': 'red',
14+
'bold': True
15+
},
16+
'info': {
17+
'color': 'cyan',
18+
'bold': True
19+
},
20+
'notice': {
21+
'color': 'magenta',
22+
'bold': True
23+
},
24+
'spam': {
25+
'color': 'green',
26+
'faint': True
27+
},
28+
'success': {
29+
'color': 'green',
30+
'bold': True
31+
},
32+
'verbose': {
33+
'color': 'blue'
34+
},
35+
'warning': {
36+
'color': 'yellow',
37+
'bold': True
38+
}
39+
}
40+
coloredlogs.install(fmt="%(asctime)s: %(message)s",
41+
datefmt='%A %Y-%m-%d %I:%M:%S %p',
42+
level="INFO")
43+
def init_logger(module):
44+
logger = logging.getLogger(module)
45+
return logger

libkloudtrader/processing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@
88
from .exceptions import OverwriteError
99

1010

11-
1211
class Buffer(Sequence):
1312
'''A doubled sided/ended queue/buffer for internal data stream processing'''
13+
1414
def __init__(self,
1515
size: int,
1616
dtype: Any = np.float32,

libkloudtrader/stocks.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1446,30 +1446,27 @@ def get_order(order_id: str,
14461446

14471447
def incoming_tick_data_handler(symbol: str, fake_feed: bool = False):
14481448
try:
1449-
latest_quote_tick=latest_quote(symbol)
1450-
latest_trade_tick=latest_trade(symbol)
1451-
latest_quote_tick['bidsize']=latest_quote_tick['bidsz']
1449+
latest_quote_tick = latest_quote(symbol)
1450+
latest_trade_tick = latest_trade(symbol)
1451+
latest_quote_tick['bidsize'] = latest_quote_tick['bidsz']
14521452
del latest_quote_tick['bidsz']
1453-
latest_quote_tick['asksize']=latest_quote_tick['asksz']
1453+
latest_quote_tick['asksize'] = latest_quote_tick['asksz']
14541454
del latest_quote_tick['asksz']
14551455
for i in latest_trade_tick:
1456-
latest_quote_tick['tradeexch']=latest_trade_tick['exch']
1457-
latest_quote_tick['price']=latest_trade_tick['last']
1458-
latest_quote_tick['tradesize']=latest_trade_tick['size']
1459-
latest_quote_tick['cvol']=latest_trade_tick['cvol']
1460-
latest_quote_tick['tradedate']=latest_trade_tick['date']
1461-
to_be_converted_to_float = numpy.array([
1462-
'price', 'ask', 'bid', 'tradesize','cvol'
1463-
])
1456+
latest_quote_tick['tradeexch'] = latest_trade_tick['exch']
1457+
latest_quote_tick['price'] = latest_trade_tick['last']
1458+
latest_quote_tick['tradesize'] = latest_trade_tick['size']
1459+
latest_quote_tick['cvol'] = latest_trade_tick['cvol']
1460+
latest_quote_tick['tradedate'] = latest_trade_tick['date']
1461+
to_be_converted_to_float = numpy.array(
1462+
['price', 'ask', 'bid', 'tradesize', 'cvol'])
14641463
for i in to_be_converted_to_float:
1465-
latest_quote_tick[i]=float(latest_quote_tick[i])
1466-
if fake_feed==True:
1467-
make_fake_price=numpy.array(['ask','price','bid'])
1468-
random_number=random.uniform(-2,2)
1464+
latest_quote_tick[i] = float(latest_quote_tick[i])
1465+
if fake_feed == True:
1466+
make_fake_price = numpy.array(['ask', 'price', 'bid'])
1467+
random_number = random.uniform(-2, 2)
14691468
for i in make_fake_price:
1470-
latest_quote_tick[i]=latest_quote_tick[i]+random_number
1469+
latest_quote_tick[i] = latest_quote_tick[i] + random_number
14711470
return latest_quote_tick
14721471
except Exception as exception:
14731472
raise exception
1474-
1475-

setup.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
long_description_content_type="text/markdown",
1313
long_description='pypi.md',
1414
install_requires=[
15-
"requests",
1615
"boto3",
1716
"pandas",
1817
"numpy",
@@ -22,6 +21,6 @@
2221
"tabulate",
2322
"ta",
2423
"TA-Lib",
25-
"streamz"
24+
"coloredlogs"
2625
],
2726
)

ta-lib/libtool

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ available_tags=" CXX"
4444

4545
# ### BEGIN LIBTOOL CONFIG
4646

47-
# Libtool was configured on host 1238e5426bdb:
47+
# Libtool was configured on host d49053c523f5:
4848

4949
# Shell to use when invoking shell scripts.
5050
SHELL="/bin/bash"
@@ -7223,7 +7223,7 @@ disable_libs=static
72237223
# End:
72247224
# ### BEGIN LIBTOOL TAG CONFIG: CXX
72257225

7226-
# Libtool was configured on host 1238e5426bdb:
7226+
# Libtool was configured on host d49053c523f5:
72277227

72287228
# Shell to use when invoking shell scripts.
72297229
SHELL="/bin/bash"

ta-lib/src/.libs/libta_lib.a

0 Bytes
Binary file not shown.

ta-lib/src/.libs/libta_lib.so.0.0.0

0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.

ta-lib/src/ta_common/ta_version.o

0 Bytes
Binary file not shown.

ta-lib/src/tools/gen_code/gen_code

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)