working on error handling

This commit is contained in:
Gert Wohlgemuth 2018-05-24 00:41:40 -07:00
parent 6689c88a7c
commit 742dc7d6d5
2 changed files with 92 additions and 79 deletions

View File

@ -56,92 +56,97 @@ def backtest(event, context):
) )
print(response) print(response)
if "Items" in response and len(response['Items']) > 0: try:
if "Items" in response and len(response['Items']) > 0:
today = datetime.datetime.today() today = datetime.datetime.today()
yesterday = today - datetime.timedelta(days=1) yesterday = today - datetime.timedelta(days=1)
content = response['Items'][0]['content'] content = response['Items'][0]['content']
configuration = { configuration = {
"max_open_trades": 1, "max_open_trades": 1,
"stake_currency": response['Items'][0]['stake_currency'], "stake_currency": response['Items'][0]['stake_currency'],
"stake_amount": 1, "stake_amount": 1,
"fiat_display_currency": "USD", "fiat_display_currency": "USD",
"unfilledtimeout": 600, "unfilledtimeout": 600,
"trailing_stop": response['Items'][0]['trailing_stop'], "trailing_stop": response['Items'][0]['trailing_stop'],
"bid_strategy": { "bid_strategy": {
"ask_last_balance": 0.0 "ask_last_balance": 0.0
}, },
"exchange": { "exchange": {
"name": response['Items'][0]['exchange'], "name": response['Items'][0]['exchange'],
"enabled": True, "enabled": True,
"key": "key", "key": "key",
"secret": "secret", "secret": "secret",
"pair_whitelist": list( "pair_whitelist": list(
map(lambda x: "{}/{}".format(x, response['Items'][0]['stake_currency']).upper(), map(lambda x: "{}/{}".format(x, response['Items'][0]['stake_currency']).upper(),
response['Items'][0]['assets'])) response['Items'][0]['assets']))
}, },
"telegram": { "telegram": {
"enabled": False, "enabled": False,
"token": "token", "token": "token",
"chat_id": "0" "chat_id": "0"
}, },
"initial_state": "running", "initial_state": "running",
"datadir": ".", "datadir": ".",
"experimental": { "experimental": {
"use_sell_signal": response['Items'][0]['use_sell'], "use_sell_signal": response['Items'][0]['use_sell'],
"sell_profit_only": True "sell_profit_only": True
}, },
"internals": { "internals": {
"process_throttle_secs": 5 "process_throttle_secs": 5
}, },
'realistic_simulation': True, 'realistic_simulation': True,
"loglevel": logging.DEBUG, "loglevel": logging.DEBUG,
"strategy": "{}:{}".format(name, content), "strategy": "{}:{}".format(name, content),
"timerange": "{}-{}".format(yesterday.strftime('%Y%m%d'), today.strftime('%Y%m%d')), "timerange": "{}-{}".format(yesterday.strftime('%Y%m%d'), today.strftime('%Y%m%d')),
"refresh_pairs": True "refresh_pairs": True
}
print("generated configuration")
print(configuration)
print("initialized backtesting")
backtesting = Backtesting(configuration)
result = backtesting.start()
print("finished test")
print("persist data in dynamo")
print(result)
result_data = []
for index, row in result.iterrows():
data = {
"id": "{}.{}:{}".format(user, name, row['currency']),
"trade": "{} to {}".format(row['entry'].strftime('%Y-%m-%d %H:%M:%S'),
row['exit'].strftime('%Y-%m-%d %H:%M:%S')),
"pair": row['currency'],
"duration": row['duration'],
"profit_percent": row['profit_percent'],
"profit_stake": row['profit_BTC'],
"entry_date": row['entry'].strftime('%Y-%m-%d %H:%M:%S'),
"exit_date": row['exit'].strftime('%Y-%m-%d %H:%M:%S')
} }
data = json.dumps(data, use_decimal=True) print("initialized backtesting")
data = json.loads(data, use_decimal=True) backtesting = Backtesting(configuration)
result = backtesting.start()
print("finished test")
print(result)
result_data = []
for index, row in result.iterrows():
data = {
"id": "{}.{}:{}".format(user, name, row['currency']),
"trade": "{} to {}".format(row['entry'].strftime('%Y-%m-%d %H:%M:%S'),
row['exit'].strftime('%Y-%m-%d %H:%M:%S')),
"pair": row['currency'],
"duration": row['duration'],
"profit_percent": row['profit_percent'],
"profit_stake": row['profit_BTC'],
"entry_date": row['entry'].strftime('%Y-%m-%d %H:%M:%S'),
"exit_date": row['exit'].strftime('%Y-%m-%d %H:%M:%S')
}
# persist data data = json.dumps(data, use_decimal=True)
trade_table.put_item(Item=data) data = json.loads(data, use_decimal=True)
result_data.append(data)
# persist data
trade_table.put_item(Item=data)
result_data.append(data)
return {
"statusCode": 200,
"body": json.dumps(result_data)
}
else:
return {
"statusCode": 404,
"body": json.dumps({
"error": "sorry we did not find any matching strategy for user {} and name {}".format(
user, name)})
}
except ImportError as e:
return { return {
"statusCode": 200, "statusCode": 500,
"body": json.dumps(result_data) "body": json.dumps({"error": e})
} }
else:
raise Exception(
"sorry we did not find any matching strategy for user {} and name {}".format(user, name))
else: else:
raise Exception("not a valid event: {}".format(event)) raise Exception("not a valid event: {}".format(event))

View File

@ -40,6 +40,12 @@ provider:
deploymentBucket: deploymentBucket:
name: lambdas-freq name: lambdas-freq
# limit the invocations a bit to avoid overloading the server
usagePlan:
throttle:
burstLimit: 100
rateLimit: 50
############################################################################################ ############################################################################################
#custom configuration settings #custom configuration settings
############################################################################################ ############################################################################################
@ -230,9 +236,11 @@ functions:
events: events:
- schedule: - schedule:
rate: rate(10 minutes) rate: rate(1440 minutes)
enabled: false
- schedule:
rate: rate(5 minutes)
enabled: true enabled: true
environment: environment:
topic: ${self:custom.snsTopic} topic: ${self:custom.snsTopic}
tradeTable: ${self:custom.tradeTable} tradeTable: ${self:custom.tradeTable}