Exemplo n.º 1
0
def fetch_data_from_api(client_id, client_secret, market, currency_pair,
                        period):

    c = ApiClient(client_id, client_secret)
    c.request_access()

    params = {
        "market": market,
        "currencyPair": currency_pair,
        "period": period
    }
    rows = c.get("https://api.cryptomon.io/api/v1/candles", params)

    row_list = []
    print("\n")
    print("Total rows from API:", len(rows))
    for row in rows:
        timestamp = row["timestamp"] / 1000
        open = row["open"]
        close = row["close"]
        high = row["high"]
        low = row["low"]
        volume = row["volume"]
        # print(timestamp, open, high, low, close, volume, close)
        row_list.append([open, high, low, close, volume, close, timestamp])

    columns = [
        'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close', 'Timestamp'
    ]
    df = pd.DataFrame(row_list, columns=columns)

    return df
 def signUrl(self, url):
     urlParts = urlparse.urlparse(url)
     pathAndQuery = urlParts.path + ("?" + urlParts.query if urlParts.query else urlParts.query)
     signed = hmac.new(self.privateKey.encode("utf-8"), ApiClient.encodeURI(pathAndQuery).encode("utf-8"), sha1)
     signature = b64encode(signed.digest()).decode("utf-8")
     if signature.endswith("="):
         signature = signature[0 : (len(signature) - 1)]
     url = url + ("&" if urlParts.query else "?") + "signature=" + ApiClient.encodeURIComponent(signature)
     return url
Exemplo n.º 3
0
 def signUrl(self, url):
     urlParts = urlparse.urlparse(url)
     pathAndQuery = urlParts.path + ('?' + urlParts.query
                                     if urlParts.query else urlParts.query)
     signed = hmac.new(self.privateKey.encode('utf-8'),
                       ApiClient.encodeURI(pathAndQuery).encode('utf-8'),
                       sha1)
     signature = b64encode(signed.digest()).decode('utf-8')
     if signature.endswith("="):
         signature = signature[0:(len(signature) - 1)]
     url = url + ('&' if urlParts.query else '?'
                  ) + "signature=" + ApiClient.encodeURIComponent(signature)
     return url
Exemplo n.º 4
0
def main(argv):
    url, key, location_name, sensor_name = process_inputs(argv)
    repository = Repository()
    repository.setup_sqlite_database()

    sensor = TSYS01.TSYS01(0x76)

    api_client = ApiClient(url, key)
    location_id = api_client.get_location_id(location_name)
    sensor_id = api_client.get_sensor_id(sensor_name)

    clean_up_db_looping_call = task.LoopingCall(clean_up_db, repository)
    clean_up_db_looping_call.start(CLEAN_UP_DB_EVERY_NUMBER_OF_HOURS * 3600)

    sync_missed_records_looping_call = task.LoopingCall(sync_missed_records, api_client, repository)
    sync_missed_records_looping_call.start(SYNC_MISSED_RECORDS_EVERY_NUMBER_OF_MINUTES * 60)

    take_reading_looping_call = task.LoopingCall(take_reading, sensor, repository, api_client, location_id, sensor_id)
    take_reading_looping_call.start(TAKE_READING_EVERY_NUMBER_OF_SECONDS)

    reactor.run()
Exemplo n.º 5
0
def request_weather(city):
    apiClienet = ApiClient(CONFIG['appid'], city.city_id)
    response = apiClienet.weather()
    response = json.loads(response.text)

    # Save weather to DB if entry for this time does not exist
    if len(Weather.get_by_unix(response['dt'])) == 0:
        weather_entry = Weather.save(city_id=city.city_id,
                                     desc=response['weather'][0]['main'],
                                     temp_max=response['main']['temp_max'],
                                     temp_min=response['main']['temp_min'],
                                     pressure=response['main']['pressure'],
                                     humidity=response['main']['humidity'],
                                     visibility=response['visibility'],
                                     wind_speed=response['wind']['speed'],
                                     dt=response['dt'])
        print("Entry for time {} added successfully".format(
            unix_to_datetime(weather_entry.dt)))
        return weather_entry
    print("Entry was not added, because it already exists for time {}".format(
        unix_to_datetime(response['dt'])))
    return None
Exemplo n.º 6
0
def sync_missed_records(api_client: ApiClient, repository: Repository):
    try:
        older_than = datetime.utcnow() - timedelta(minutes=ONLY_SYNC_MISSED_RECORDS_OLDER_THAN_NUMBER_OF_MINUTES)
        missed_readings = repository.get_unsynced_readings(MAX_NUMBER_OF_RECORDS_TO_SYNC_AT_ONCE, older_than)
        if len(missed_readings) == 0:
            print(f"Re-sync: Everything is already synced. Exiting.")
            return

        print(f"Re-sync: Syncing {len(missed_readings)} missed records.")
        result_code = api_client.post_db_temperature_readings(missed_readings)
        if result_code in (200, 201):
            repository.mark_readings_synced(list(map(lambda x: x.id, missed_readings)))
            print(f"Re-sync: Successfully synced {len(missed_readings)} records.")
            return

        print(f"Re-sync: Failed. Status code: {result_code}")
    except Exception as e:
        print("Re-sync: Failed.", e)
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('commands', metavar='cmd', nargs='+',
                        help='commands to operate')
    parser.add_argument('--zone')
    args = parser.parse_args()

    apiClient = ApiClient(os.environ['AUTODNS_USERNAME'], os.environ['AUTODNS_PASSWORD'],
                          os.getenv('AUTODNS_CONTEXT', '4'))

    for cmd in args.commands:
        if cmd == 'zone-list':
            ZoneList(apiClient).run()
        elif cmd == 'zone-info':
            ZoneInfo(apiClient).run(args.zone)
        else:
            sys.exit("Unknown command: " + cmd)

    return 0
Exemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-z', '--zone', nargs='+', help='<Required> Set flag')
    parser.add_argument('-d',
                        '--domain',
                        nargs='+',
                        help='<Required> Set flag')
    parser.add_argument('-k', '--key', nargs='+', help='<Required> Set flag')
    parser.add_argument('--zone-system_ns', help='Zone System Nameserver')
    parser.add_argument('--rr-name', help='Resource Record Name')
    parser.add_argument('--rr-type', help='Resource Record Type')
    parser.add_argument('--rr-ttl', help='Resource Record TTL Seconds')
    parser.add_argument('--rr-value', help='Resource Record Value')
    parser.add_argument('--output_format', help='Specify output format (csv)')
    parser.add_argument(
        'commands',
        metavar='cmd',
        nargs='+',
        help=
        'commands to operate (zone-list, zone-info, zone-update, domain-list, domain-info)'
    )
    args = parser.parse_args()

    apiClient = ApiClient(os.environ['AUTODNS_USERNAME'],
                          os.environ['AUTODNS_PASSWORD'],
                          os.getenv('AUTODNS_CONTEXT', '4'))

    for cmd in args.commands:
        if cmd == 'zone-list':
            ZoneList(apiClient).run()
        elif cmd == 'zone-info':
            return ZoneInfo(apiClient).run(args)
        elif cmd == 'zone-update':
            ZoneUpdate(apiClient).run(args)
        elif cmd == 'domain-list':
            DomainList(apiClient).run()
        elif cmd == 'domain-info':
            DomainInfo(apiClient).run(args.domain, args.key)
        else:
            sys.exit("Unknown command: " + cmd)

    return 0
Exemplo n.º 9
0
def before_request():
    g.cc = CommonConfig()
    g.ac = ApiClient(commonconfig=g.cc)
Exemplo n.º 10
0
                                   ylim=(-10, 120))  # 60min KDJ线
    ax_60min_kdj.set_title("60Min KDJ")

    line_k_of_1min, = ax_1min_kdj.plot([], [], lw=2)  # 1min KDJ K线
    line_d_of_1min, = ax_1min_kdj.plot([], [], lw=2)  # 1min KDJ D线
    line_j_of_1min, = ax_1min_kdj.plot([], [], lw=2)  # 1min KDJ J线

    line_k_of_15min, = ax_15min_kdj.plot([], [], lw=2)  # 15min KDJ K线
    line_d_of_15min, = ax_15min_kdj.plot([], [], lw=2)  # 15min KDJ D线
    line_j_of_15min, = ax_15min_kdj.plot([], [], lw=2)  # 15min KDJ J线

    line_k_of_60min, = ax_60min_kdj.plot([], [], lw=2)  # 60min KDJ K线
    line_d_of_60min, = ax_60min_kdj.plot([], [], lw=2)  # 60min KDJ D线
    line_j_of_60min, = ax_60min_kdj.plot([], [], lw=2)  # 60min KDJ J线

    client = ApiClient()

    symbol = Symbol(Symbol.BTC, Symbol.USDT).get_symbol()

    xs_of_1min = []
    ks_of_1min = []
    ds_of_1min = []
    js_of_1min = []

    xs_of_15min = []
    ks_of_15min = []
    ds_of_15min = []
    js_of_15min = []

    xs_of_60min = []
    ks_of_60min = []