Skip to content

Commit

Permalink
adding more candle scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
Dave Pettypiece committed Oct 21, 2016
1 parent 22f405c commit 97351a1
Show file tree
Hide file tree
Showing 11 changed files with 454 additions and 61 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: bootstrap
bootstrap:
virtualenv env
env/bin/pip install -r requirements.txt
env/bin/pip install -r requirements/base.txt
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,18 @@ with the provided entry point alias:
```


## Transaction Scripts
## Instrument Scripts

### Polling Transactions
### Fetch Instrument Candlesticks

The script to fetch instrument candlesticks is defined at
`src/instrument/candles.py`. It can be executed directly or with the provided
entry point alias:

```bash
(env)user@host: ~/v20-python-samples$ python src/instrument/candles.py
(env)user@host: ~/v20-python-samples$ v20-instrument-candles
```

### Streaming Transactions

File renamed without changes.
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
'v20-account-summary = account.summary:main',
'v20-account-instruments = account.instruments:main',
'v20-account-changes = account.changes:main',
'v20-account-configure = account.configure:main',
'v20-instrument-candles = instrument.candles:main',
'v20-instrument-candles-follow = instrument.candles_follow:main',
]
}
)
Expand Down
83 changes: 29 additions & 54 deletions src/account/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import select
import argparse
import common.config
from common.view import print_response_transaction
from account import Account


def main():
"""
Create an API context, and use it to fetch an Account state and then
Expand All @@ -24,10 +26,15 @@ def main():
common.config.add_argument(parser)

parser.add_argument(
"--poll-interval",
type=int,
default=5,
help="The number of seconds between polls for Account changes"
"--margin-rate",
default=None,
help="The new default margin rate for the Account"
)

parser.add_argument(
"--alias",
default=None,
help="The new alias for the Account"
)

args = parser.parse_args()
Expand All @@ -40,62 +47,30 @@ def main():
#
api = args.config.create_context()

kwargs = {}

if args.alias is not None:
kwargs["alias"] = args.alias

if args.margin_rate is not None:
kwargs["marginRate"] = args.margin_rate

#
# Fetch the details of the Account found in the config file
#
response = api.account.get(account_id)
response = api.account.configure(account_id, **kwargs)

#
# Extract the Account representation from the response and use
# it to create an Account wrapper
#
account = Account(
response.get("account", "200")
if response.status == 200:
print "Success"
print

print_response_transaction(
response,
"200",
"Configure Transaction",
"configureTransaction"
)

def dump():
account.dump()

print "Press <ENTER> to see current state for Account {}".format(
account.details.id
)

dump()

while True:
i, o, e = select.select([sys.stdin], [], [], args.poll_interval)

if i:
sys.stdin.readline()
dump()

#
# Poll for all changes to the account since the last
# Account Transaction ID that was seen
#
response = api.account.changes(
account_id,
sinceTransactionID=account.details.lastTransactionID
)

account.apply_changes(
response.get(
"changes",
"200"
)
)

account.apply_state(
response.get(
"state",
"200"
)
)

account.details.lastTransactionID = response.get(
"lastTransactionID",
"200"
)

if __name__ == "__main__":
main()
18 changes: 15 additions & 3 deletions src/common/arg_helper.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
def parse_instrument(i):
i.replace("/", "_")
return i
from datetime import datetime
import argparse

def instrument(i):
return i.replace("/", "_")

def date_time(fmt="%Y-%m-%d %H:%M:%S"):
def parse(s):
try:
return datetime.strptime(s, fmt)
except ValueError:
msg = "Not a valid date: '{0}'.".format(s)
raise argparse.ArgumentTypeError(msg)

return parse
2 changes: 1 addition & 1 deletion src/common/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def print_collection(title, entities, columns):
(
body,
headers,
tablefmt=tablefmt
tablefmt=tablefmt,
).encode('utf-8')
)
print
Expand Down
Empty file added src/instrument/__init__.py
Empty file.
152 changes: 152 additions & 0 deletions src/instrument/candles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#!/usr/bin/env python

import argparse
import common.config
import common.arg_helper
from view import CandlePrinter
from datetime import datetime


def main():
"""
Create an API context, and use it to fetch candles for an instrument.
The configuration for the context is parsed from the config file provided
as an argumentV
"""

parser = argparse.ArgumentParser()

#
# The config object is initialized by the argument parser, and contains
# the REST APID host, port, accountID, etc.
#
common.config.add_argument(parser)

parser.add_argument(
"--instrument",
type=common.arg_helper.instrument,
default=None,
help="The instrument to get candles for"
)

parser.add_argument(
"--mid",
action='store_true',
help="Get midpoint-based candles"
)

parser.add_argument(
"--bid",
action='store_true',
help="Get bid-based candles"
)

parser.add_argument(
"--ask",
action='store_true',
help="Get ask-based candles"
)

parser.add_argument(
"--smooth",
action='store_true',
help="'Smooth' the candles"
)

parser.set_defaults(mid=False, bid=False, ask=False)

parser.add_argument(
"--granularity",
default=None,
help="The candles granularity to fetch"
)

parser.add_argument(
"--count",
default=None,
help="The number of candles to fetch"
)

date_format = "%Y-%m-%d %H:%M:%S"

parser.add_argument(
"--from-time",
default=None,
type=common.arg_helper.date_time(),
help="The start date for the candles to be fetched. Format is 'YYYY-MM-DD HH:MM:SS'"
)

parser.add_argument(
"--to-time",
default=None,
type=common.arg_helper.date_time(),
help="The end date for the candles to be fetched. Format is 'YYYY-MM-DD HH:MM:SS'"
)

args = parser.parse_args()

account_id = args.config.active_account

#
# The v20 config object creates the v20.Context for us based on the
# contents of the config file.
#
api = args.config.create_context()

kwargs = {}

if args.granularity is not None:
kwargs["granularity"] = args.granularity

if args.smooth is not None:
kwargs["smooth"] = args.smooth

if args.count is not None:
kwargs["count"] = args.count

if args.from_time is not None:
kwargs["fromTime"] = args.from_time.strftime("%Y-%m-%dT%H:%M:%S.000000000Z")

if args.to_time is not None:
kwargs["toTime"] = args.to_time.strftime("%Y-%m-%dT%H:%M:%S.000000000Z")

price = "mid"

if args.mid:
kwargs["price"] = "M" + kwargs.get("price", "")
price = "mid"

if args.bid:
kwargs["price"] = "B" + kwargs.get("price", "")
price = "bid"

if args.ask:
kwargs["price"] = "A" + kwargs.get("price", "")
price = "ask"

#
# Fetch the candles
#
response = api.instrument.candles(args.instrument, **kwargs)

if response.status != 200:
print response
print response.body
return

print "Instrument: {}".format(response.get("instrument", 200))
print "Granularity: {}".format(response.get("granularity", 200))

printer = CandlePrinter()

printer.print_header()

candles = response.get("candles", 200)

for candle in response.get("candles", 200):
printer.print_candle(candle)


if __name__ == "__main__":
main()
Loading

0 comments on commit 97351a1

Please sign in to comment.