Author

Topic: [PHP| BTC-E arbitrage bot (Read 22080 times)

sr. member
Activity: 686
Merit: 253
March 01, 2017, 03:45:47 PM
#48
Thanks for sharing, I will try to run it tomorrow and PM you if I have any problems thanks.
newbie
Activity: 1
Merit: 0
March 01, 2017, 02:46:23 PM
#47
Hi
This is such a great thread. Thank you all for contributing! Smiley
 :)You guys are really good with this type of thing.

I only wish I knew how to install and run it, since I am new to both bitcoin and programming.

I have a website and it seems like I must run this on the website, correct? Huh

What is my first or next step, please?
member
Activity: 70
Merit: 10
December 30, 2016, 11:58:15 AM
#46
Thats buddy for showing it to us .it will be very helpful and bringing to us the concept of php .it was surely very helpful.
full member
Activity: 238
Merit: 100
November 01, 2016, 10:49:01 AM
#45
Hello there, you know anything about PHP because I don't.

There is no need digging up an old topic if you only want to introduce yourself Grin

Just hang around and chat with people.
newbie
Activity: 1
Merit: 0
November 01, 2016, 09:20:19 AM
#44
hi
full member
Activity: 182
Merit: 100
January 16, 2014, 09:26:28 PM
#43
It's a command line only server. I can get array successfully by "w3m https://btc-e.com/api/2/ltc_usd/depth".

It's so strange I get another error message last night:

Code:
PHP Warning:  file_get_contents(https://btc-e.com/api/2/ltc_btc/depth): failed to open stream: HTTP request failed! HTTP/1.1 502 Bad Gateway
 in /home/myname/script/btc-e.php on line 118

I am trying it with sudo now
hero member
Activity: 938
Merit: 1001
January 16, 2014, 09:07:58 PM
#42
Does the machine running the script have a web browser? If so, what happens when you go to this page?

https://btc-e.com/api/2/ltc_usd/depth

You should see an array of the LTC_USD order books.
full member
Activity: 182
Merit: 100
January 16, 2014, 01:13:55 AM
#41
Does PHP have access to internet?

I believe so because it can retrieve data from BTC-E in the beginning

BTC-E Arbitrage Bot v0.1 (CTRL+C to exit)
Trade amount (min/increment/max): 0.01 / 0.02 / 0.06
Minimum profit: 1 %
Price margin: 1.05
Delay between checks: 200 ms
Min time between trades: 10 s
14:11:58 Balance: X USD, X BTC, X LTC

I restart it from time to time to make sure API is not banned by BTC-E

hero member
Activity: 938
Merit: 1001
January 16, 2014, 01:02:42 AM
#40
I have no idea about this error

Code:
PHP Warning:  file_get_contents(https://btc-e.com/api/2/ltc_usd/depth): failed to open stream:
HTTP request failed! HTTP/1.1 520 Origin Error

It come from this line

Code:
$orders = file_get_contents('https://btc-e.com/api/2/' . $pair . '/depth');

I am running it with "php xxxx.php" in a linux server. Does it mean my location is restricted for API?

Does PHP have access to internet?
full member
Activity: 182
Merit: 100
January 15, 2014, 07:41:09 PM
#39
I have no idea about this error

Code:
PHP Warning:  file_get_contents(https://btc-e.com/api/2/ltc_usd/depth): failed to open stream:
HTTP request failed! HTTP/1.1 520 Origin Error

It come from this line

Code:
$orders = file_get_contents('https://btc-e.com/api/2/' . $pair . '/depth');

I am running it with "php xxxx.php" in a linux server. Does it mean my location is restricted for API?
newbie
Activity: 8
Merit: 0
January 13, 2014, 10:47:46 PM
#38
does anyone have a made a good result for this bot?
newbie
Activity: 37
Merit: 0
January 13, 2014, 12:04:15 AM
#37
Could anyone explain me the proper settings for either XAMP or WAMP?

Thanks in advance


It seems to be working now, though it the php explorer it still states

Code:
Fatal error: Maximum execution time of 30 seconds exceeded in D:\Apps\Wamp\www\bot_mad_livekey.php on line 122

# Time Memory Function Location
1 0.0007 307720 {main}( ) ..\bot_mad_livekey.php:0
2 0.0007 310592 main_loop( ) ..\bot_mad_livekey.php:283
3 29.8922 822544 order_book( ) ..\bot_mad_livekey.php:199


Which is:

Code:
$orders = file_get_contents('https://btc-e.com/api/2/' . $pair . '/depth');

So it probably stalls on getting the order_book as stated before

Maybe this extra information helps somebody to find the solution?

I`ll put up a bounty of 0.01BTC for the one that is able to fix it

php has a default execution time. Try putting this at the top of the script

ini_set('max_execution_time', 0);
sr. member
Activity: 262
Merit: 250
January 07, 2014, 01:19:03 AM
#35
where is the new code?
sr. member
Activity: 266
Merit: 250
December 29, 2013, 12:25:05 PM
#34
I haven't used it in months but it did work for me.

I have been using the new code released by miaviator.

Timmieman got this one running but also moved on to the new code.

Nice. Thanks!
hero member
Activity: 938
Merit: 1001
December 29, 2013, 12:17:23 PM
#33
I haven't used it in months but it did work for me.

I have been using the new code released by miaviator.

Timmieman got this one running but also moved on to the new code.
member
Activity: 116
Merit: 11
December 25, 2013, 02:23:33 PM
#32
Ok, I managed to make it work but (at least with the current settings) the algorithm seems to lose money Smiley.

Example of a set of transactions:

LTC/BTC   sell   2.0563 LTC   0.029 BTC   0.0596327 BTC   25.12.13 15:47
LTC/USD   buy   2.0563 LTC   19 USD   39.0697 USD   25.12.13 15:47
BTC/USD   sell   0.059 BTC   652.126 USD   38.475434 USD   25.12.13 15:47


So basically at the end of the transactions i'm:

BTC: + 0.0006326
LTC: 0
USD: - 0.594266


Since 0.0006326 BTC in USD (at the rate of 652.126) is just -0.4126001202 I lost ~0.2 USD Smiley

What am I mising?


member
Activity: 116
Merit: 11
December 24, 2013, 03:47:20 AM
#31
I'm running the bot with the following settings, but no transactions appear to happen in over 12h (there is also no other message in the console). Is this normal?

BTC-E Arbitrage Bot v0.1 (CTRL+C to exit)
Trade amount (min/increment/max): 0.001 / 0.0002 / 0.006
Minimum profit: 1 %
Price margin: 1.05
Delay between checks: 1000 ms
Min time between trades: 10 s
10:42:03 Balance: 62.9649178 USD, 0.0463 BTC, 1.996 LTC
sr. member
Activity: 266
Merit: 250
December 23, 2013, 09:16:06 PM
#30
Hey btc-mike

Are you still running this bot?

Has it worked for you?
full member
Activity: 194
Merit: 100
December 23, 2013, 05:52:50 AM
#29
Could anyone explain me the proper settings for either XAMP or WAMP?

Thanks in advance


It seems to be working now, though it the php explorer it still states

Code:
Fatal error: Maximum execution time of 30 seconds exceeded in D:\Apps\Wamp\www\bot_mad_livekey.php on line 122

# Time Memory Function Location
1 0.0007 307720 {main}( ) ..\bot_mad_livekey.php:0
2 0.0007 310592 main_loop( ) ..\bot_mad_livekey.php:283
3 29.8922 822544 order_book( ) ..\bot_mad_livekey.php:199


Which is:

Code:
$orders = file_get_contents('https://btc-e.com/api/2/' . $pair . '/depth');

So it probably stalls on getting the order_book as stated before

Maybe this extra information helps somebody to find the solution?

I`ll put up a bounty of 0.01BTC for the one that is able to fix it

Are you running it from the command line? It appears that php is limiting the execution time
full member
Activity: 136
Merit: 100
December 03, 2013, 05:52:40 AM
#28
Could anyone explain me the proper settings for either XAMP or WAMP?

Thanks in advance


It seems to be working now, though it the php explorer it still states

Code:
Fatal error: Maximum execution time of 30 seconds exceeded in D:\Apps\Wamp\www\bot_mad_livekey.php on line 122

# Time Memory Function Location
1 0.0007 307720 {main}( ) ..\bot_mad_livekey.php:0
2 0.0007 310592 main_loop( ) ..\bot_mad_livekey.php:283
3 29.8922 822544 order_book( ) ..\bot_mad_livekey.php:199


Which is:

Code:
$orders = file_get_contents('https://btc-e.com/api/2/' . $pair . '/depth');

So it probably stalls on getting the order_book as stated before

Maybe this extra information helps somebody to find the solution?

I`ll put up a bounty of 0.01BTC for the one that is able to fix it
hero member
Activity: 938
Merit: 1001
December 02, 2013, 09:19:41 PM
#27
Pulling the order books doesn't require curl. Curl is used later in the program.

I don't know anything about XAMPP setup.
full member
Activity: 136
Merit: 100
December 02, 2013, 06:35:59 PM
#26
I enabled curl in php.ini of XAMPP.

Is theresomething else I should configure?

Thanks in advance
hero member
Activity: 938
Merit: 1001
December 01, 2013, 10:04:13 PM
#25
Code looks like mine.

I think your XAMPP is screwed up. I asked you about it before. Getting the order books is the simple part of accessing BTC-e. Since the bot is tripping up on that, there is probably an issue with your configs.
full member
Activity: 136
Merit: 100
November 30, 2013, 11:04:53 AM
#24
I did not make any changes as far as i can remember:

Also, if I just enter the link in my URL it puts out the specific data I need, therefore i`m quite confused what the problem might be

This is my complete code:


Code:

// Trade API settings
$key 'Deletedddd'// your API-key
$secret 'Deleteddddd'// your Secret-key

// Limits for trading size (BTC)
// Setting the increment too small will have a negative effect on speed
$min_amount 0.01;
$max_amount 0.06;
$increment 0.002;

// Minimum profit in percent
// Must be higher than BTC-E fee * 3 to be profitable
$min_profit 1.0;

// Margin of price
// Trades will be executed this much higher/lower to make "sure" they go through
// 1.05 = 5 % and so on
$price_margin 1.05;

// Delay between requests (ms), check with BTC-E how high value they allow
// setting this too high could cause BTC-E to potentially block the bot.
$delay 300;

// Specify a minimum time between 2 trades (s). Whenever an inbalance between prices exists
// we want to quickly execute the FIRST trade, but let other arbitrage bots (with bigger balances)
// clean up the rest. Otherwise there seems to be big risk for losing trades.
$time_between_trades 10;
$last_trade_time 0;

// Required for BTC-E API
$mt explode(' 'microtime());
$nonce $mt[1];

// http://pastebin.com/QyjS3U9M
function btce_query($method, array $req = array())
{
global $key$secret$nonce;

$req['method'] = $method;
$req['nonce'] = $nonce++;

// generate the POST data string
$post_data http_build_query($req'''&');

$sign hash_hmac("sha512"$post_data$secret);

// generate the extra headers
$headers = array(
'Sign: '.$sign,
'Key: '.$key,
);

// our curl handle (initialize if required)
static $ch null;
if (is_null($ch)) {
$ch curl_init();
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_USERAGENT'Mozilla/4.0 (compatible; BTC-E PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
}
curl_setopt($chCURLOPT_URL'https://btc-e.com/tapi/');
curl_setopt($chCURLOPT_POSTFIELDS$post_data);
curl_setopt($chCURLOPT_HTTPHEADER$headers);
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);

// run the query
$res curl_exec($ch);
if ($res === false)
exit('Trade API error: Connection error: ' curl_error($ch));

$dec json_decode($restrue);
if (!$dec)
exit('Trade API error: Invalid JSON.');

return $dec;
}

function 
perform_trade($trade$show_balance)
{
global $last_trade_time;

$last_trade_time time();

$reply btce_query('Trade'$trade);

if ($reply['success'] != 1)
exit('Trade error: ' $reply['error']);

if ($show_balance)
print_balance($reply);
}

function 
print_balance($response false)
{
if (!$response)
$response btce_query('getInfo');

$str "";

foreach ($response['return']['funds'] as $key => $val)
{
if ($val 0)
{
if (strlen($str) > 0)
$str .= ",";

$str .= " " $val " " strtoupper($key);
}
}

echo date("H:i:s") . ' Balance:' $str "\n";
}

// Fetch order book for a given currency pair
function order_book($pair)
{
$orders file_get_contents('https://btc-e.com/api/2/' $pair '/depth');

if ($orders === false)
exit('Public API error: Connection error.');

$dec json_decode($orders);
if (!$dec)
echo date("H:i:s") . " ERROR: Unable to fetch order book for " $pair ".\n";

return $dec;
}

// Return how big volume we can get with the given amount
function ask_volume($orders$amount)
{
$vol 0;
$value 0;

for ($i 0$i count($orders->asks) && $value $amount$i++)
{
$this_value min($orders->asks[$i][0] * $orders->asks[$i][1], $amount $value);
$this_vol $this_value $orders->asks[$i][0];

$value += $this_value;
$vol += $this_vol;
}

return $vol;
}

function 
bid_volume($orders$amount)
{
$vol 0;
$value 0;

for ($i 0$i count($orders->bids) && $value $amount$i++)
{
$this_value min($orders->bids[$i][1], $amount $value);
$this_vol $this_value $orders->bids[$i][0];

$value += $this_value;
$vol += $this_vol;
}

return $vol;
}

function 
best_bid($orders)
{
return $orders->bids[0][0];
}

function 
best_ask($orders)
{
return $orders->asks[0][0];
}

// The main function of the program
function main_loop()
{
global $min_amount$max_amount$increment$min_profit$delay$price_margin$time_between_trades$last_trade_time;

// Print some starting information
echo "BTC-E Arbitrage Bot v0.1 (CTRL+C to exit)\n";
echo "Trade amount (min/increment/max): " $min_amount " / " $increment " / " $max_amount "\n";
echo "Minimum profit: " $min_profit " %\n";
echo "Price margin: " $price_margin "\n";
echo "Delay between checks: " $delay " ms\n";
echo "Min time between trades: " $time_between_trades " s\n";

print_balance();

// Loop indefinitely (press CTRL+C to exit)
while (true)
{
// Fetch order books for all currency pairs
$btc_usd_orders order_book('btc_usd');
$ltc_btc_orders order_book('ltc_btc');
$ltc_usd_orders order_book('ltc_usd');

// Proceed if we have orders for all pairs
if ($btc_usd_orders && $ltc_btc_orders && $ltc_usd_orders)
{
$best_case 0;
$best_profit 0;
$best_amount 0;
$best_trades = array();

// Loop through different order sizes to find the one with most profit
for ($amt $min_amount$amt <= $max_amount$amt += $increment)
{
// Case 1: BTC -> LTC -> USD -> BTC
$c1_ltc ask_volume($ltc_btc_orders$amt);
$c1_usd bid_volume($ltc_usd_orders$c1_ltc);
$c1_btc ask_volume($btc_usd_orders$c1_usd);

$c1_profit $c1_btc $amt;
$c1_profit_percent = ($c1_profit 100) / $amt;

if ($c1_profit $best_profit && $c1_profit_percent $min_profit)
{
$best_case 1;
$best_profit $c1_profit;
$best_amount $amt;
$best_trades = array
(
array('pair' => 'ltc_btc''type' => 'buy''amount' => round($c1_ltc6), 'rate' => round(best_ask($ltc_btc_orders) * $price_margin3)),
array('pair' => 'ltc_usd''type' => 'sell''amount' => round($c1_ltc6), 'rate' => round(best_bid($ltc_usd_orders) / $price_margin3)),
array('pair' => 'btc_usd''type' => 'buy''amount' => round($c1_btc6), 'rate' => round(best_ask($btc_usd_orders) * $price_margin3))
);
}

// Case 2: BTC -> USD -> LTC -> BTC
$c2_usd bid_volume($btc_usd_orders$amt);
$c2_ltc ask_volume($ltc_usd_orders$c2_usd);
$c2_btc bid_volume($ltc_btc_orders$c2_ltc);

$c2_profit $c2_btc $amt;
$c2_profit_percent = ($c2_profit 100) / $amt;

if ($c2_profit $best_profit && $c2_profit_percent $min_profit)
{
$best_case 2;
$best_profit $c2_profit;
$best_amount $amt;
$best_trades = array
(
array('pair' => 'btc_usd''type' => 'sell''amount' => round($amt6), 'rate' => round(best_bid($btc_usd_orders) / $price_margin3)),
array('pair' => 'ltc_usd''type' => 'buy''amount' => round($c2_ltc6), 'rate' => round(best_ask($ltc_usd_orders) * $price_margin3)),
array('pair' => 'ltc_btc''type' => 'sell''amount' => round($c2_ltc6), 'rate' => round(best_bid($ltc_btc_orders) / $price_margin3))
);
}
}

// Execute the trades if we found one
if ($best_case 0)
{
echo date("H:i:s") . ($best_case == " LTC -> USD" " USD -> LTC") . ", Amount " $best_amount .
", Expected Profit " number_format($best_profit4) .
" (" number_format(($best_profit 100) / $best_amount2) . " %)\n";

// Check that enough time has passed from the last trade
if ((time() - $last_trade_time) < $time_between_trades)
{
echo date("H:i:s") . " Rejected (not enough time passed from last trade.\n";
}
else
{
perform_trade($best_trades[0], false);
perform_trade($best_trades[1], false);
perform_trade($best_trades[2], true);
}
}
}

// Sleep for a bit
usleep($delay 1000);
}
}

// Execute the main loop function
main_loop();

hero member
Activity: 938
Merit: 1001
November 29, 2013, 03:18:07 PM
#23
Did you make any changes? If so, post the code here.

Is your XAMPP setup correctly? Have you used it successfully with any other programs.
full member
Activity: 136
Merit: 100
November 29, 2013, 01:15:45 PM
#22
I`ve been trying to get this bot to work though it keeps spitting out the same error:

Code:
Warning: file_get_contents(https://btc-e.com/api/2/btc_usd/depth): failed to open stream: Invalid argument in D:\Apps\XAMPP\bot.php on line 118

Public API error: Connection error

My IP is not blacklisted or anything, it still pumps out values.

Does anyone know how this could be fixed?

With best regards,
Tim
vip
Activity: 756
Merit: 503
November 20, 2013, 11:46:37 AM
#21
It is not my work. You can contact MadAlpha
hero member
Activity: 640
Merit: 771
BTC⇆⚡⇄BTC
November 19, 2013, 11:30:03 PM
#20
Greetings!

Nice script. Thanks for sharing it.

It's been a while since BTC-e, Vircurex and Cryptsy added some more altcoins.

BTW, is it possible to add automated (triangular and 2-currency) arbitrage for altcoins pairs (LTC/BTC; NMC/BTC; PPC/BTC; XPM/BTC etc.)?

Keep up the good work!
vip
Activity: 756
Merit: 503
September 19, 2013, 11:34:48 AM
#19
so how do I implement this/?
You need PHP and curl installed then put your BTC-E API key at the appropriate place in the code.
sr. member
Activity: 294
Merit: 250
September 19, 2013, 10:24:41 AM
#18
so how do I implement this/?
vip
Activity: 756
Merit: 503
September 18, 2013, 05:48:17 AM
#17
100ms? That is crazy ... I never used intervals < 15s in my bots.

It might work for you now, but if all those hundreds of bots switch to such a scheme, the website is blocked ...

100ms on my home connection is over 300ms in reality.
legendary
Activity: 965
Merit: 1000
September 18, 2013, 03:59:43 AM
#16
100ms? That is crazy ... I never used intervals < 15s in my bots.

It might work for you now, but if all those hundreds of bots switch to such a scheme, the website is blocked ...
hero member
Activity: 938
Merit: 1001
September 17, 2013, 05:05:19 PM
#15
Agreed - not too hard to fix.

After I was white-listed, I hit them harder with no issues. You just need to ask to be white-listed.
vip
Activity: 756
Merit: 503
September 17, 2013, 02:52:21 PM
#14
It's easy to fix so it will never time-out on an error but it might give unwanted results. Like I said in my second post you need to adjust the timing so BTC-E won't ban your IP. Mine got banned temporarily a couple time before I got the settings right. It will vary depending on your connection, it wasn't the same on my home connection vs a VPS. Officialy they say once every 10 minutes but if I remember right I was able to use 300ms on my VPS and 100ms on my home connection.
hero member
Activity: 938
Merit: 1001
September 17, 2013, 02:48:52 PM
#13
Would anyone be interested in posting the results of running this script for some amount of time? (I'm thinking minimum 3 days).

Notes on what kind of balancing is necessary will be helpful as well.

You want me to test for 3 days and share my settings and results? NO

I will share this.

1. As is, the program will time out long before 3 days. The code that pulls the books will error out. I have run it on few hosted systems and they both timed out (one lasted a lot longer).

2. You will end up blacklisted at btc-e if you hit them too hard. Open a support ticket and they can whitelist your IP.
full member
Activity: 182
Merit: 100
September 17, 2013, 10:59:53 AM
#12
Would anyone be interested in posting the results of running this script for some amount of time? (I'm thinking minimum 3 days).

Notes on what kind of balancing is necessary will be helpful as well.
sr. member
Activity: 364
Merit: 250
September 17, 2013, 09:49:03 AM
#11
Thanks for sharing Smiley
jr. member
Activity: 59
Merit: 10
September 14, 2013, 08:19:43 AM
#10
Thanks for share Cheesy
hero member
Activity: 938
Merit: 1001
September 13, 2013, 12:11:58 PM
#9
I have made another bot that checks multiple paths (based on this ->https://bitcointalksearch.org/topic/btc-e-php-currency-arbitrage-bot-full-code-196313) but I still use this one. This one found a profitable trade path yesterday.
full member
Activity: 154
Merit: 100
September 04, 2013, 06:44:20 PM
#8
Thanks for sharing this bot.  Wink
hero member
Activity: 938
Merit: 1001
September 04, 2013, 02:33:21 PM
#7
Anyone play with this?

I am running on my shared hosting with about 0.1BTC. It seems to make a little bit.
sr. member
Activity: 259
Merit: 250
June 21, 2013, 01:16:22 AM
#6
It does log every trade on the screen and return error message.

I did not run it for a very long time. I can't tell if it's profitable.

Unfortunately, as with any automated system , you would need an extremely large sample size to determine the relative profitability (or lack there of.)

Running it in short bursts will likely give you very skewed results based on variance.

Unless you have an excellent idea of what you are doing and are willing to risk a large amount of currency to tune it (as well as deal with extended drawdowns), I would recommend staying away from such things.
vip
Activity: 756
Merit: 503
June 17, 2013, 10:13:05 PM
#5
It does log every trade on the screen and return error message.

I did not run it for a very long time. I can't tell if it's profitable.
full member
Activity: 294
Merit: 100
June 17, 2013, 10:09:22 PM
#4
Thank you for sharing.  What has your experience been with this bot?  Was it successful, did you see a profit?  How long have you had this code?  Also, I assume it does not output anything until something happens?
vip
Activity: 756
Merit: 503
June 17, 2013, 01:52:13 AM
#3
Some fine tuning need to be done like min/max amount. If you run it on a VPS with low latency then 100ms delay will get the bot a temp ban from BTC-E. Still a very nice code for those who want to learn.
sr. member
Activity: 308
Merit: 250
Jack of oh so many trades.
June 17, 2013, 01:46:31 AM
#2
Thanks for sharing!
vip
Activity: 756
Merit: 503
June 17, 2013, 01:36:01 AM
#1
I paid for this bot but I'm giving it to the community for free.
You need to have some amount of currency in all 3 currencies (USD/LTC/BTC) to use it. Then as you run it, your USD/LTC balance will decrement and your BTC balance will increment.

Code:

// Trade API settings
$key ''// your API-key
$secret ''// your Secret-key

// Limits for trading size (BTC)
// Setting the increment too small will have a negative effect on speed
$min_amount 0.1;
$max_amount 0.6;
$increment 0.02;

// Minimum profit in percent
// Must be higher than BTC-E fee * 3 to be profitable
$min_profit 1.0;

// Margin of price
// Trades will be executed this much higher/lower to make "sure" they go through
// 1.05 = 5 % and so on
$price_margin 1.05;

// Delay between requests (ms), check with BTC-E how high value they allow
// setting this too high could cause BTC-E to potentially block the bot.
$delay 100;

// Specify a minimum time between 2 trades (s). Whenever an inbalance between prices exists
// we want to quickly execute the FIRST trade, but let other arbitrage bots (with bigger balances)
// clean up the rest. Otherwise there seems to be big risk for losing trades.
$time_between_trades 10;
$last_trade_time 0;

// Required for BTC-E API
$mt explode(' 'microtime());
$nonce $mt[1];

// http://pastebin.com/QyjS3U9M
function btce_query($method, array $req = array())
{
global $key$secret$nonce;

$req['method'] = $method;
$req['nonce'] = $nonce++;

// generate the POST data string
$post_data http_build_query($req'''&');

$sign hash_hmac("sha512"$post_data$secret);

// generate the extra headers
$headers = array(
'Sign: '.$sign,
'Key: '.$key,
);

// our curl handle (initialize if required)
static $ch null;
if (is_null($ch)) {
$ch curl_init();
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_USERAGENT'Mozilla/4.0 (compatible; BTC-E PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
}
curl_setopt($chCURLOPT_URL'https://btc-e.com/tapi/');
curl_setopt($chCURLOPT_POSTFIELDS$post_data);
curl_setopt($chCURLOPT_HTTPHEADER$headers);
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);

// run the query
$res curl_exec($ch);
if ($res === false)
exit('Trade API error: Connection error: ' curl_error($ch));

$dec json_decode($restrue);
if (!$dec)
exit('Trade API error: Invalid JSON.');

return $dec;
}

function 
perform_trade($trade$show_balance)
{
global $last_trade_time;

$last_trade_time time();

$reply btce_query('Trade'$trade);

if ($reply['success'] != 1)
exit('Trade error: ' $reply['error']);

if ($show_balance)
print_balance($reply);
}

function 
print_balance($response false)
{
if (!$response)
$response btce_query('getInfo');

$str "";

foreach ($response['return']['funds'] as $key => $val)
{
if ($val 0)
{
if (strlen($str) > 0)
$str .= ",";

$str .= " " $val " " strtoupper($key);
}
}

echo date("H:i:s") . ' Balance:' $str "\n";
}

// Fetch order book for a given currency pair
function order_book($pair)
{
$orders file_get_contents('https://btc-e.com/api/2/' $pair '/depth');

if ($orders === false)
exit('Public API error: Connection error.');

$dec json_decode($orders);
if (!$dec)
echo date("H:i:s") . " ERROR: Unable to fetch order book for " $pair ".\n";

return $dec;
}

// Return how big volume we can get with the given amount
function ask_volume($orders$amount)
{
$vol 0;
$value 0;

for ($i 0$i count($orders->asks) && $value $amount$i++)
{
$this_value min($orders->asks[$i][0] * $orders->asks[$i][1], $amount $value);
$this_vol $this_value $orders->asks[$i][0];

$value += $this_value;
$vol += $this_vol;
}

return $vol;
}

function 
bid_volume($orders$amount)
{
$vol 0;
$value 0;

for ($i 0$i count($orders->bids) && $value $amount$i++)
{
$this_value min($orders->bids[$i][1], $amount $value);
$this_vol $this_value $orders->bids[$i][0];

$value += $this_value;
$vol += $this_vol;
}

return $vol;
}

function 
best_bid($orders)
{
return $orders->bids[0][0];
}

function 
best_ask($orders)
{
return $orders->asks[0][0];
}

// The main function of the program
function main_loop()
{
global $min_amount$max_amount$increment$min_profit$delay$price_margin$time_between_trades$last_trade_time;

// Print some starting information
echo "BTC-E Arbitrage Bot v0.1 (CTRL+C to exit)\n";
echo "Trade amount (min/increment/max): " $min_amount " / " $increment " / " $max_amount "\n";
echo "Minimum profit: " $min_profit " %\n";
echo "Price margin: " $price_margin "\n";
echo "Delay between checks: " $delay " ms\n";
echo "Min time between trades: " $time_between_trades " s\n";

print_balance();

// Loop indefinitely (press CTRL+C to exit)
while (true)
{
// Fetch order books for all currency pairs
$btc_usd_orders order_book('btc_usd');
$ltc_btc_orders order_book('ltc_btc');
$ltc_usd_orders order_book('ltc_usd');

// Proceed if we have orders for all pairs
if ($btc_usd_orders && $ltc_btc_orders && $ltc_usd_orders)
{
$best_case 0;
$best_profit 0;
$best_amount 0;
$best_trades = array();

// Loop through different order sizes to find the one with most profit
for ($amt $min_amount$amt <= $max_amount$amt += $increment)
{
// Case 1: BTC -> LTC -> USD -> BTC
$c1_ltc ask_volume($ltc_btc_orders$amt);
$c1_usd bid_volume($ltc_usd_orders$c1_ltc);
$c1_btc ask_volume($btc_usd_orders$c1_usd);

$c1_profit $c1_btc $amt;
$c1_profit_percent = ($c1_profit 100) / $amt;

if ($c1_profit $best_profit && $c1_profit_percent $min_profit)
{
$best_case 1;
$best_profit $c1_profit;
$best_amount $amt;
$best_trades = array
(
array('pair' => 'ltc_btc''type' => 'buy''amount' => round($c1_ltc6), 'rate' => round(best_ask($ltc_btc_orders) * $price_margin3)),
array('pair' => 'ltc_usd''type' => 'sell''amount' => round($c1_ltc6), 'rate' => round(best_bid($ltc_usd_orders) / $price_margin3)),
array('pair' => 'btc_usd''type' => 'buy''amount' => round($c1_btc6), 'rate' => round(best_ask($btc_usd_orders) * $price_margin3))
);
}

// Case 2: BTC -> USD -> LTC -> BTC
$c2_usd bid_volume($btc_usd_orders$amt);
$c2_ltc ask_volume($ltc_usd_orders$c2_usd);
$c2_btc bid_volume($ltc_btc_orders$c2_ltc);

$c2_profit $c2_btc $amt;
$c2_profit_percent = ($c2_profit 100) / $amt;

if ($c2_profit $best_profit && $c2_profit_percent $min_profit)
{
$best_case 2;
$best_profit $c2_profit;
$best_amount $amt;
$best_trades = array
(
array('pair' => 'btc_usd''type' => 'sell''amount' => round($amt6), 'rate' => round(best_bid($btc_usd_orders) / $price_margin3)),
array('pair' => 'ltc_usd''type' => 'buy''amount' => round($c2_ltc6), 'rate' => round(best_ask($ltc_usd_orders) * $price_margin3)),
array('pair' => 'ltc_btc''type' => 'sell''amount' => round($c2_ltc6), 'rate' => round(best_bid($ltc_btc_orders) / $price_margin3))
);
}
}

// Execute the trades if we found one
if ($best_case 0)
{
echo date("H:i:s") . ($best_case == " LTC -> USD" " USD -> LTC") . ", Amount " $best_amount .
", Expected Profit " number_format($best_profit4) .
" (" number_format(($best_profit 100) / $best_amount2) . " %)\n";

// Check that enough time has passed from the last trade
if ((time() - $last_trade_time) < $time_between_trades)
{
echo date("H:i:s") . " Rejected (not enough time passed from last trade.\n";
}
else
{
perform_trade($best_trades[0], false);
perform_trade($best_trades[1], false);
perform_trade($best_trades[2], true);
}
}
}

// Sleep for a bit
usleep($delay 1000);
}
}

// Execute the main loop function
main_loop();

Credit: MadAlpha

If you enjoy this post you can send me a donation.

BTC: 1DB5BC85mqwdQbJaed47tWFpmn96i1YyWn
LTC: LahP2YUhSiJQaupn2AYB2iUgRSFg3n57uZ
Jump to: