Skip to content

Instantly share code, notes, and snippets.

@artpi
Forked from levelsio/btc-eth-dca-buy.php
Last active October 14, 2021 16:39
Show Gist options
  • Save artpi/1ba44adf05cdc59fa0d150abecdbc97b to your computer and use it in GitHub Desktop.
Save artpi/1ba44adf05cdc59fa0d150abecdbc97b to your computer and use it in GitHub Desktop.
This script runs daily and "Dollar Cost Average"-buys $40 BTC and $10 ETH per day
<?php
// Forked from @levelsio
function generateBitstampSignature( $nonce ) {
$message = $nonce . BITSTAMP_ID . BITSTAMP_KEY;
return strtoupper( hash_hmac( 'sha256', $message, BITSTAMP_SECRET ) );
}
function bitstamp_request( $url, $payload = array() ) {
$mt = explode( ' ', microtime() );
$nonce = $mt[1] . substr( $mt[0], 2, 6 );
$fields = array_merge( $payload, array(
'key' => urlencode( BITSTAMP_KEY ),
'signature' => urlencode( generateBitstampSignature( $nonce ) ),
'nonce' => urlencode( $nonce ),
) );
//url-ify the data for the POST
$postdata = http_build_query( $fields );
$opts = array(
'http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create( $opts );
$result = file_get_contents( $url, false, $context );
return json_decode( $result, true );
}
//
$conf = Utils::getFirebaseData( 'btc/daily-buy' );
$text = "Bitcoin:";
foreach ( $conf as $ticker => $amount ){
$amount = floatval( $amount );
if ( $amount > 0 ) {
$t = strtoupper( $ticker );
// get price
$url = "https://www.bitstamp.net/api/v2/ticker/$ticker";
$reply = json_decode( file_get_contents( $url ), true );
$btc_price = $reply['ask'];
Utils::log( LOG_INFO, "$t Price: " . $btc_price );
// if BTC price outlier, exit
if ( $btc_price < 1000 || $btc_price > 100000 ) {
Utils::log( LOG_WARNING, "Exiting because price either <1,000 or >100,000" );
Utils::slack( "Bitcoin: Price out of parameter: $btc_price","Bitcoin" , "bitcoin" );
exit;
}
$btcToBuy = round( $amount / $btc_price, 8 );
$msg = "Buying " . $amount . " of $t, which equals " . $btcToBuy;
Utils::log( LOG_INFO,$msg );
$text .= "\n{$msg}: ";
$result = bitstamp_request( "https://www.bitstamp.net/api/v2/buy/market/$ticker/", array( 'amount' => urlencode( $btcToBuy ) ) );
if ( ! empty( $result['status'] ) && $result['status'] === 'error' ) {
Utils::log( LOG_ERR, print_r( $result['reason'], true ) );
$text .= "ERROR";
} else {
Utils::log( LOG_DEBUG, print_r( $result, true ) );
$text .= "OK";
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment