This commit is contained in:
discountry
2025-10-03 15:28:16 +08:00
parent d5c4b04746
commit fcb83bd16b
925 changed files with 165721 additions and 4 deletions
+160
View File
@@ -0,0 +1,160 @@
<style>ul { margin-bottom: -10px; }</style>
# [<-](Examples?id=php)
# CCXT PHP Examples
To run PHP examples from any folder type in console:
```shell
php -f path/to/example.php # substitute for actual filename here
```
- [Arbitrage Pairs](./examples/php/arbitrage-pairs.md)
- [Async Await Fetch Multiple](./examples/php/async-await-fetch-multiple.md)
- [Async Await Fetch](./examples/php/async-await-fetch.md)
- [Basic Error Handling](./examples/php/basic-error-handling.md)
- [Basic Order](./examples/php/basic-order.md)
- [Binance Create Order Stop Loss Take Profit](./examples/php/binance-create-order-stop-loss-take-profit.md)
- [Binance Fetch All Trades For All Traded Symbols](./examples/php/binance-fetch-all-trades-for-all-traded-symbols.md)
- [Binance Oco Order](./examples/php/binance-oco-order.md)
- [Binance Set Futures Leverage](./examples/php/binance-set-futures-leverage.md)
- [Binance Spot Trailing](./examples/php/binance-spot-trailing.md)
- [Bitfinex2 Fetch Ohlcv Since Limit](./examples/php/bitfinex2-fetch-ohlcv-since-limit.md)
- [Bitfinex2 Fetch Ohlcv](./examples/php/bitfinex2-fetch-ohlcv.md)
- [Bitfinex2 Fetch Trades Since](./examples/php/bitfinex2-fetch-trades-since.md)
- [Bitmex Create Order](./examples/php/bitmex-create-order.md)
- [Build Ohlcv Bars](./examples/php/build-ohlcv-bars.md)
- [Built In Rate Limiting Poller](./examples/php/built-in-rate-limiting-poller.md)
- [Bybit Updated](./examples/php/bybit-updated.md)
- [Bytetrade Create Order](./examples/php/bytetrade-create-order.md)
- [Cache Exchange Instance Reuse](./examples/php/cache-exchange-instance-reuse.md)
- [Cancel Order](./examples/php/cancel-order.md)
- [Cli](./examples/php/cli.md)
- [Coinbase Fetch All Balances](./examples/php/coinbase-fetch-all-balances.md)
- [Coinbasepro Cursor Pagination](./examples/php/coinbasepro-cursor-pagination.md)
- [Coinone Markets](./examples/php/coinone-markets.md)
- [Compare Two Exchanges Capabilities](./examples/php/compare-two-exchanges-capabilities.md)
- [Create Order Position With Takeprofit Stoploss](./examples/php/create-order-position-with-takeprofit-stoploss.md)
- [Create Order Ws Example](./examples/php/create-order-ws-example.md)
- [Create Orders Example](./examples/php/create-orders-example.md)
- [Create Trailing Amount Order](./examples/php/create-trailing-amount-order.md)
- [Create Trailing Percent Order](./examples/php/create-trailing-percent-order.md)
- [Error Handling Message](./examples/php/error-handling-message.md)
- [Exchange Properties](./examples/php/exchange-properties.md)
- [Fetch Balance](./examples/php/fetch-balance.md)
- [Fetch First Ohlcv Timestamp](./examples/php/fetch-first-ohlcv-timestamp.md)
- [Fetch Ohlcv Many Exchanges Continuosly](./examples/php/fetch-ohlcv-many-exchanges-continuosly.md)
- [Fetch Ohlcv](./examples/php/fetch-ohlcv.md)
- [Fetch Order](./examples/php/fetch-order.md)
- [Fetch Ticker](./examples/php/fetch-ticker.md)
- [Fetch Tickers](./examples/php/fetch-tickers.md)
- [Gateio Futures](./examples/php/gateio-futures.md)
- [Gateio Swaps](./examples/php/gateio-swaps.md)
- [Huobi Fetch Balance](./examples/php/huobi-fetch-balance.md)
- [Huobi Futures](./examples/php/huobi-futures.md)
- [Huobi Swaps](./examples/php/huobi-swaps.md)
- [Indodax Fetch Balance Create Order Cancel Order](./examples/php/indodax-fetch-balance-create-order-cancel-order.md)
- [Kraken Create And Close Position](./examples/php/kraken-create-and-close-position.md)
- [Kraken Query Ledgers](./examples/php/kraken-query-ledgers.md)
- [Kucoin Fetch All Deposit Addresses](./examples/php/kucoin-fetch-all-deposit-addresses.md)
- [Kucoin Implicit Inner Transfer V1](./examples/php/kucoin-implicit-inner-transfer-v1.md)
- [Latoken Example](./examples/php/latoken-example.md)
- [Load All At Once Async](./examples/php/load-all-at-once-async.md)
- [Load All At Once](./examples/php/load-all-at-once.md)
- [Margin Loan Borrow Buy Sell Repay](./examples/php/margin-loan-borrow-buy-sell-repay.md)
- [Method Overload Override](./examples/php/method-overload-override.md)
- [Nonce Override](./examples/php/nonce-override.md)
- [Order Book Level Depth Extra Param](./examples/php/order-book-level-depth-extra-param.md)
- [Phemex Create Order Position With Takeprofit Stoploss](./examples/php/phemex-create-order-position-with-takeprofit-stoploss.md)
- [Proxy Usage](./examples/php/proxy-usage.md)
- [React Eventloop With Rate Limiting](./examples/php/react-eventloop-with-rate-limiting.md)
- [Sample Local Proxy Server With Cors](./examples/php/sample-local-proxy-server-with-cors.md)
- [Shared Markets](./examples/php/shared-markets.md)
- [Symbols](./examples/php/symbols.md)
- [Trading View](./examples/php/trading-view.md)
- [Watch Ohlcv For Symbols](./examples/php/watch-OHLCV-For-Symbols.md)
- [Watch Ohlcv](./examples/php/watch-OHLCV.md)
- [Watch Orderbook For Symbols](./examples/php/watch-OrderBook-For-Symbols.md)
- [Watch Trades For Symbols](./examples/php/watch-Trades-For-Symbols.md)
- [Watch Tickers](./examples/php/watch-tickers.md)
- [Watchohlcvforsymbols](./examples/php/watchOHLCVForSymbols.md)
- [Watchorderbookforsymbols](./examples/php/watchOrderBookForSymbols.md)
- [Watchpositions Many Exchanges Continuosly](./examples/php/watchPositions-many-exchanges-continuosly.md)
- [Watchpositions](./examples/php/watchPositions.md)
- [Watchpositionsforsymbols](./examples/php/watchPositionsForSymbols.md)
- [Watchtradesforsymbols](./examples/php/watchTradesForSymbols.md)
@@ -0,0 +1,144 @@
- [Arbitrage Pairs](./examples/php/)
```php
<?php
include './ccxt.php';
include 'Console/Table.php'; // pear-install it from here: https://pear.php.net/package/Console_Table/
date_default_timezone_set('UTC');
function style ($s, $style) { return $style . $s . "\033[0m"; }
function green ($s) { return style ($s, "\033[92m"); }
function blue ($s) { return style ($s, "\033[94m"); }
function yellow ($s) { return style ($s, "\033[93m"); }
function red ($s) { return style ($s, "\033[91m"); }
function pink ($s) { return style ($s, "\033[95m"); }
function bold ($s) { return style ($s, "\033[1m"); }
function underline ($s) { return style ($s, "\033[4m"); }
function dump ($s) { echo implode (' ', func_get_args ()) . "\n"; }
function print_supported_exchanges () {
$exchanges = \ccxt\Exchange::$exchanges;
dump ('Supported exchanges:', green (implode (', ', $exchanges)));
}
function flatten ($array) {
return array_reduce ($array, function ($acc, $item) {
return array_merge ($acc, is_array ($item) ? flatten ($item) : [$item]);
}, []);
}
function tabulate ($headers, $rows) {
$tbl = new Console_Table();
$tbl->setHeaders ($headers);
$tbl->addData ($rows);
return $tbl->getTable ();
}
function pairs_table_helper ($pair) {
return array_values ($pair);
}
$proxies = array (
'', // no proxy by default
'https://crossorigin.me/',
'https://cors-anywhere.herokuapp.com/',
);
$max_retries = count ($proxies);
$ids = array_slice ($argv, 1);
$exchanges = array ();
$min_exchanges = 2; // a pair should be present on at least two exchanges or more
if ($ids) {
// load all markets from all exchanges
foreach ($ids as $id) {
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $id;
$exchange = new $exchange ();
// save it in an assoc array for later use
$exchanges[$id] = $exchange;
$current_proxy = 0;
for ($num_retries = 0; $num_retries < $max_retries; $num_retries++) {
try {
$exchange->proxy = $proxies[$current_proxy];
$current_proxy = (++$current_proxy) % count ($proxies);
// load all markets from the exchange
$markets = $exchange->load_markets ();
// output a list of all market symbols
dump (green ($id), 'has', yellow (count ($exchange->symbols)), 'symbols');
break;
} catch (\ccxt\RequestTimeout $e) {
print_r ($e);
} catch (\ccxt\DDoSProtection $e) {
print_r ($e);
} catch (\ccxt\AuthenticationError $e) {
print_r ($e);
} catch (\ccxt\ExchangeNotAvailable $e) {
print_r ($e);
} catch (\ccxt\NotSupported $e) {
print_r ($e);
} catch (\ccxt\NetworkError $e) {
print_r ($e);
} catch (\ccxt\ExchangeError $e) {
print_r ($e);
} catch (Exception $e) {
print_r ($e);
}
}
}
dump (green ('Loaded all markets'));
$all_symbols = flatten (array_values (array_map (function ($exchange) {
return $exchange->symbols;
}, $exchanges)));
$unique_symbols = array_unique ($all_symbols);
// filter unique symbols leaving those present on at least 2 exchanges or more
$arbitrable_symbols = array_filter ($unique_symbols, function ($symbol) use (&$exchanges, $min_exchanges) {
$num_related_exchanges = count (array_filter ($exchanges, function ($exchange) use (&$symbol, $min_exchanges) {
return in_array ($symbol, $exchange->symbols);
}));
return ($num_related_exchanges >= $min_exchanges);
});
sort ($arbitrable_symbols);
$pairs = array_map (function ($symbol) use (&$exchanges) {
$result = array ('symbol' => $symbol);
foreach ($exchanges as $exchange) {
$result[$exchange->id] = in_array ($symbol, $exchange->symbols) ? $exchange->id : '';
}
return $result;
}, $arbitrable_symbols);
// output a table of all markets
@dump (tabulate (array_keys ($pairs[0]), array_map ('pairs_table_helper', $pairs)));
} else {
dump ('Usage: php -f', __FILE__, green ('id'));
print_supported_exchanges ();
}
?>
```
@@ -0,0 +1,28 @@
- [Async Await Fetch Multiple](./examples/php/)
```php
<?php
// Instead of yield generators, now users can use modern Async/Await syntax
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
date_default_timezone_set('UTC');
use function React\Async\async;
use function React\Async\await;
use function React\Promise\all;
$exchange = new ccxt\async\binance([]);
await($exchange->load_markets());
$symbols = array('BTC/USDT', 'ETH/USDT', 'DOGE/USDT');
echo "########### Combined await ###########\n";
$promises = [];
foreach ($symbols as $symbol) {
$promises[] = $exchange->fetch_ticker($symbol);
}
$tickers = await(all($promises));
echo "{$tickers[0]['symbol']} {$tickers[0]['close']} | {$tickers[1]['symbol']} {$tickers[1]['close']} | {$tickers[21]['symbol']} {$tickers[2]['close']}\n";
```
@@ -0,0 +1,64 @@
- [Async Await Fetch](./examples/php/)
```php
<?php
// Instead of yield generators, now users can use modern Async/Await syntax
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
use function React\Async\async;
use function React\Async\await;
date_default_timezone_set('UTC');
$exchange = new ccxt\async\binance([]);
await($exchange->load_markets());
$symbols = array('BTC/USDT', 'ETH/USDT');
// ###########################################
echo "########## Individual await ##########\n";
foreach ($symbols as $symbol) {
$ticker = await($exchange->fetch_ticker($symbol));
echo "{$ticker['symbol']} {$ticker['close']}\n";
}
// ###########################################
// ###########################################
echo "########### Combined await ###########\n";
$promises = [];
foreach ($symbols as $symbol) {
$promises[] = $exchange->fetch_ticker($symbol);
}
$tickers = await(React\Promise\all($promises));
echo "{$tickers[0]['symbol']} {$tickers[0]['close']} | {$tickers[1]['symbol']} {$tickers[1]['close']}\n";
// ###########################################
// ###########################################
$exchange->fetch_ticker($symbols[0])->then(function($ticker){
echo "########## Callback->then ##########\n";
echo "{$ticker['symbol']} {$ticker['close']}\n";
});
// ###########################################
// ################### custom async function ########################
function myFunc ($exchange, $symbol) {
return async(function () use ($exchange, $symbol) {
try {
// example sleep
await(React\Promise\Timer\sleep(0.5));
$ticker = await($exchange->fetch_ticker($symbol));
echo "########## Custom async function ##########\n";
echo "{$ticker['symbol']} {$ticker['close']}\n";
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
}
});
}
await(myFunc($exchange, $symbols[0])());
// ###########################################
```
@@ -0,0 +1,31 @@
- [Basic Error Handling](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\bittrex ();
$message = null;
try {
$result = $exchange->fetch_ticker ('NONEXISTENT_SYMBOL');
var_dump ($result);
} catch (Exception $e) {
// print it
echo $e->getMessage() . "\n";
// save to $message (for whatever needs)
$message = $e->getMessage();
}
?>
```
@@ -0,0 +1,42 @@
- [Basic Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\binance (array(
'apiKey' => 'YOUR_API_KEY', // change for your keys
'secret' => 'YOUR_API_SECRET',
));
$message = null;
try {
$exchange->load_markets();
$exchange->verbose = true; // uncomment for debugging purposes
// adjust your values below
$symbol = 'BTC/USDT';
$order_type = 'limit';
$side = 'sell';
$amount = 0.123; // adjust for your amount
$price = 50000; // adjust for your price (for limit orders)
$result = $exchange->create_order ($symbol, $order_type, $side, $amount, $price);
var_dump ($result);
} catch (Exception $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,55 @@
- [Binance Create Order Stop Loss Take Profit](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
echo 'PHP v' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION . "\n";
echo 'CCXT v' . \ccxt\Exchange::VERSION . "\n";
$id = 'binanceusdm'; // edit this line
// ----------------------------------------------------------------------------
// instantiate the exchange by id
$exchange_class = '\\ccxt\\' . $id;
$exchange = new $exchange_class(array(
// some exchanges may require additional API credentials
'apiKey' => 'YOUR_API_KEY', // edit this line
'secret' => 'YOUR_SECRET', // edit this line
));
$exchange->load_markets();
// $exchange->verbose = True; // uncomment for debugging purposes
$symbol = 'BTC/USDT';
$side = 'buy';
$amount = 0.01;
$stopLossPrice = 25000;
$takeProfitPrice = 35000;
try {
$order = $exchange->create_order($symbol, 'MARKET', $side, $amount);
print_r($order);
$inverted_side = ($side == 'buy') ? 'sell' : 'buy';
$stopLossParams = array('stopPrice' => $stopLossPrice);
$stopLossOrder = $exchange->create_order($symbol, 'STOP_MARKET', $inverted_side, $amount, null, $stopLossParams);
print_r($stopLossOrder);
$takeProfitParams = array('stopPrice' => $takeProfitPrice);
$takeProfitOrder = $exchange->create_order($symbol, 'TAKE_PROFIT_MARKET', $inverted_side , $amount, null, $takeProfitParams);
print_r($takeProfitOrder);
} catch (Exception $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
}
```
@@ -0,0 +1,113 @@
- [Binance Fetch All Trades For All Traded Symbols](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$id = "\\ccxt\\binance";
$exchange = new $id(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
));
$exchange->load_markets();
$balance = $exchange->fetch_balance();
$total = $balance['total'];
$all_matching_symbols = array();
foreach ($total as $currency_code => $value) {
echo "-------------------------------------------------------------------\n";
echo "Currency code: ", $currency_code, " value: ", $value, "\n";
if ($value > 0) {
// get all related markets with
// either base currency === currency code from the balance structure
// or quote currency === currency code from the balance structure
$matching_markets = array_filter(array_values($exchange->markets), function ($market) use ($currency_code) {
return ($market['base'] === $currency_code) || ($market['quote'] === $currency_code);
});
$matching_symbols = $exchange->pluck($matching_markets, 'symbol');
echo "Matching symbols:\n";
print_r($matching_symbols);
$all_matching_symbols = array_merge($all_matching_symbols, $matching_symbols);
}
}
echo "========================================================================\n";
$unique_symbols = $exchange->unique($all_matching_symbols);
print_r($unique_symbols);
$all_trades_for_all_symbols = array();
// ----------------------------------------------------------------------------
function fetch_all_my_trades($exchange, $symbol) {
$from_id = '0';
$params = array('fromId' => $from_id);
$previous_from_id = $from_id;
$all_trades = array();
while (true) {
echo "------------------------------------------------------------------\n";
echo "Fetching with params:\n";
print_r($params);
$trades = $exchange->fetch_my_trades($symbol, null, null, $params);
echo "Fetched ", count($trades), ' ', $symbol, " trades\n";
if (count($trades)) {
$last_trade = $trades[count($trades) - 1];
if ($last_trade['id'] == $previous_from_id) {
break;
} else {
$params['fromId'] = $last_trade['id'];
$previous_from_id = $last_trade['id'];
$all_trades = array_merge ($all_trades, $trades);
}
} else {
break;
}
}
echo "Fetched ", count($all_trades), ' ', $symbol, " trades\n";
for ($i = 0; $i < count($all_trades); $i++) {
$trade = $all_trades[$i];
echo $i, ' ', $trade['symbol'], ' ', $trade['id'], ' ', $trade['datetime'], ' ', $trade['amount'], "\n";
}
return $all_trades;
}
// ----------------------------------------------------------------------------
foreach ($unique_symbols as $symbol) {
echo "=================================================================\n";
echo "Fetching all ", $symbol, " trades\n";
// fetch all trades for the $symbol, with pagination
$trades = fetch_all_my_trades($exchange, $symbol);
echo count($trades), ' ' , $symbol, " trades\n";
$all_trades_for_all_symbols = array_merge($all_trades_for_all_symbols, $trades);
}
// do whatever you want with $all_trades_for_all_symbols
?>
```
@@ -0,0 +1,69 @@
- [Binance Oco Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\binance(array(
'apiKey' => 'YOUR_API_KEY', // replace with your keys
'secret' => 'YOUR_SECRET',
'verbose' => true,
));
try {
$symbol = 'XRP/BTC'; // replace with your symbol
$amount = 123.45; // replace with your amount here
$price = 543.21; // replace with your price here
$stop_price = 123.45; // replace with your stop_price
// $limit_iceberg_qty = 543.21; // replace with your limit iceberg amount
// if stopLimitPrice is provided, stopLimitTimeInForce is also required
// $stop_limit_price = 54.321; // replace with your stop limit price
// $stop_limit_time_in_force = 'GTC'; // or 'FOK', or 'IOC'
// $stop_iceberg_qty = 123.45; // replace with your stop iceberg amount
// https://github.com/ccxt/ccxt/wiki/Manual#loading-markets
$exchange->load_markets();
// https://github.com/ccxt/ccxt/wiki/Manual#symbols-and-market-ids
$market = $exchange->market($symbol);
// https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods
$params = array(
'symbol' => $market['id'], // market id
// 'listClientOrderId' => 'STRING', // a unique id for the entire orderList
'side' => 'BUY', // or 'SELL'
'quantity' => $exchange->amount_to_precision($symbol, $amount), // decimal string
// 'limitClientOrderId' => 'STRING', // a unique id for the limit order
'price' => $exchange->price_to_precision($symbol, $price), // decimal string
// 'limitIcebergQty' => $exchange->amount_to_precision($symbol, $limit_iceberg_qty), // decimal string
// 'stopClientOrderId' => 'STRING', // a unique id for the stop loss/stop loss limit leg
'stopPrice' => $exchange->price_to_precision($symbol, $stop_price), // decimal string
// if stopLimitPrice is provided, stopLimitTimeInForce is also required
// 'stopLimitPrice' => $exchange->price_to_precision($symbol, $stop_limit_price), // decimal string
// 'stopLimitTimeInForce' => $stop_limit_time_in_force,
// 'stopIcebergQty' => $exchange->amount_to_precision($symbol, $stop_iceberg_qty), // decimal string
// 'newOrderRespType' => 'ACK', // or 'RESULT', or 'FULL', // set the response JSON
);
$response = $exchange->private_post_order_oco($params);
var_dump($response);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,41 @@
- [Binance Set Futures Leverage](./examples/php/)
```php
<?php
include './ccxt.php';
// https://github.com/ccxt/ccxt/wiki/Manual#instantiation
date_default_timezone_set('UTC');
$exchange_id = 'binance';
$exchange_class = "\\ccxt\\$exchange_id";
$exchange = new $exchange_class(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
'options' => array(
'defaultType' => 'future'
),
));
$exchange->load_markets(); // https://github.com/ccxt/ccxt/wiki/Manual#loading-markets
// $exchange->verbose = true; // verbose mode on, uncomment for debugging
$symbol = 'BTC/USDT';
$market = $exchange->market($symbol);
// https://github.com/ccxt/ccxt/wiki/Manual#passing-parameters-to-api-methods
$params = array(
'symbol' => $market['id'], // convert a unified CCXT symbol to an exchange-specific market id
'leverage' => 10,
);
// https://github.com/ccxt/ccxt/wiki/Manual#implicit-api-methods
$response = $exchange->fapiPrivate_post_leverage($params);
print_r ($response);
```
@@ -0,0 +1,79 @@
- [Binance Spot Trailing](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
echo 'CCXT v' . \ccxt\Exchange::VERSION . "\n";
$exchange = new \ccxt\binance(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET_KEY',
// 'verbose' => true, // uncomment if debug output is needed
));
// You can read more about spot trailing orders here:
// https://github.com/binance/binance-spot-api-docs/blob/master/faqs/trailing-stop-faq.md
// Example 1: Spot : trailing spot loss
function example_1($exchange) {
$markets = $exchange->load_markets(true);
// create STOP_LOSS_LIMIT BUY with a trailing stop of 5%.
$symbol = 'LTC/USDT';
$type = 'STOP_LOSS_LIMIT';
$side = 'buy';
$amount = 0.4;
$price = 25;
$params = array(
'trailingDelta' => 500, // 5% in BIPS
);
$create_order = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r('Create order id:' . $create_order['id']);
// cancel created order
$canceled_order = $exchange->cancel_order($create_order['id'] . $symbol);
print_r ($canceled_order);
}
// -----------------------------------------------------------------------------------------
// Example 2: Spot : TAKE_PROFIT_LIMIT BUY order
function example_2($exchange) {
$markets = $exchange->load_markets(true);
// create STOP_LOSS_LIMIT BUY with a trailing stop of 5%.
$symbol = 'LTC/USDT';
$type = 'TAKE_PROFIT_LIMIT';
$side = 'buy';
$amount = 0.2;
$price = 70;
$params = array(
'trailingDelta' => 250, // 2.5% in BIPS
);
$create_order = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r('Create order id:' . $create_order['id']);
// cancel created order
$canceled_order = $exchange->cancel_order($create_order['id'], $symbol);
print_r ($canceled_order);
}
// -----------------------------------------------------------------------------------------
function main($exchange) {
example_1($exchange);
example_2($exchange);
}
main($exchange)
?>
```
@@ -0,0 +1,32 @@
- [Bitfinex2 Fetch Ohlcv Since Limit](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
// instantiate the exchange by id
$exchange = '\\ccxt\\bitfinex2';
$exchange = new $exchange();
// load all markets from the exchange
$markets = $exchange->load_markets();
function run($exchange, $symbol, $timeframe, $since, $limit) {
$ohlcvs = $exchange->fetch_ohlcv($symbol, $timeframe, $since, $limit);
foreach ($ohlcvs as $v) {
printf ("%s O:%.8f H:%.8f L:%.8f C:%.8f V:%.8f\n", $exchange->iso8601($v[0]), $v[1], $v[2], $v[3], $v[4], $v[5]);
}
}
printf("--------------------------------------------------------------\n");
run($exchange, 'ETH/BTC', '1m', 1518842513569, 5);
printf("--------------------------------------------------------------\n");
run($exchange, 'ETH/BTC', '1m', 1518842513569, 10);
printf("--------------------------------------------------------------\n");
?>
```
@@ -0,0 +1,24 @@
- [Bitfinex2 Fetch Ohlcv](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = '\\ccxt\\bitfinex2';
$exchange = new $exchange(array(
'rateLimit' => 12000,
));
// bitfinex2 breaks occasionally
for ($i = 0; $i < 1000; $i++) {
$ohlcv = $exchange->fetch_ohlcv('BTC/USD', '1m');
print_r ($exchange->iso8601($ohlcv[0][0]) . "\t" . count($ohlcv) . "\n");
}
?>
```
@@ -0,0 +1,26 @@
- [Bitfinex2 Fetch Trades Since](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$id = 'bitfinex2';
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $id;
$exchange = new $exchange ();
// load all markets from the exchange
$trades = $exchange->fetch_trades ('ETH/BTC', 1518983548636 - 2 * 24 * 60 * 60 * 1000);
foreach ($trades as $trade) {
echo $trade['datetime'] . "\n";
}
echo count ($trades) . " trades\n";
?>
```
@@ -0,0 +1,31 @@
- [Bitmex Create Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\bitmex(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET',
));
$symbol = 'BTC/USD:BTC-220624';
$type = 'StopLimit'; // # or 'market', or 'Stop' or 'StopLimit'
$side = 'sell'; // or 'buy'
$amount = 1.0;
$price = 6500.0; // or None
// extra params and overrides
$params = array(
'stopPx' => 6000.0, // if needed
);
$order = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r($order);
```
@@ -0,0 +1,80 @@
- [Build Ohlcv Bars](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// Bulding OHLCV array from trades (executions) data is a bit tricky. For example, if you want to build 100 ohlcv bars of 1-minute timeframe, then you have to fetch the 100 minutes of trading data. So, higher timeframe bars require more trading data (i.e. building 100 bars of 1-day timeframe OHLCV would require massive amount of trading data, which might not be desirable for user, because of data-usage rate limits)
function example_with_fetch_trades() {
return Async\async(function () {
$exch = new \ccxt\async\binance(array());
$timeframe = '1m';
$symbol = 'OGN/USDT';
$since = $exch->milliseconds() - 1000 * 60 * 30; // last 30 mins
$limit = 1000;
$trades = Async\await($exch->fetch_trades($symbol, $since, $limit));
$generated_bars = $exch->build_ohlcvc($trades, $timeframe, $since, $limit);
// you can ignore 6th index ("count" field) from ohlcv entries, which is not part of OHLCV standard structure and is just added internally by `buildOHLCVC` method
var_dump('[REST] Constructed', count($generated_bars), 'bars from trades: ', $generated_bars);
}) ();
}
function example_with_watch_trades() {
return Async\async(function () {
$exch = new \ccxt\pro\binance(array());
$timeframe = '1m';
$symbol = 'DOGE/USDT';
$limit = 1000;
$since = $exch->milliseconds() - 10 * 60 * 1000 * 1000; // last 10 hrs
$collected_trades = [];
$collected_bars = [];
while (true) {
$ws_trades = Async\await($exch->watch_trades($symbol, $since, $limit, array()));
$collected_trades = array_merge($collected_trades, $ws_trades);
$generated_bars = $exch->build_ohlcvc($collected_trades, $timeframe, $since, $limit);
// Note: first bar would be partially constructed bar and its 'open' & 'high' & 'low' prices (except 'close' price) would probably have different values compared to real bar on chart, because the first obtained trade timestamp might be somewhere in the middle of timeframe period, so the pre-period would be missing because we would not have trades data. To fix that, you can get older data with `fetchTrades` to fill up bars till start bar.
for ($i = 0; $i < count($generated_bars); $i++) {
$bar = $generated_bars[$i];
$bar_timestamp = $bar[0];
$collected_bars_length = count($collected_bars);
$last_collected_bar_timestamp = $collected_bars_length > 0 ? $collected_bars[$collected_bars_length - 1][0] : 0;
if ($bar_timestamp === $last_collected_bar_timestamp) {
// if timestamps are same, just updarte the last bar
$collected_bars[$collected_bars_length - 1] = $bar;
} elseif ($bar_timestamp > $last_collected_bar_timestamp) {
$collected_bars[] = $bar;
// remove the trades from saved array, which were till last collected bar's open timestamp
$collected_trades = $exch->filter_by_since_limit($collected_trades, $bar_timestamp);
}
}
// Note: first bar would carry incomplete values, please read comment in "buildOHLCVCFromWatchTrades" method definition for further explanation
var_dump('[WS] Constructed', count($collected_bars), 'bars from', $symbol, 'trades: ', $collected_bars);
}
}) ();
}
Async\await(example_with_fetch_trades());
Async\await(example_with_watch_trades());
```
@@ -0,0 +1,24 @@
- [Built In Rate Limiting Poller](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = '\\ccxt\\poloniex';
$exchange = new $exchange();
$symbol = 'DOGE/BTC';
while (true) {
$order_book = $exchange->fetch_order_book($symbol);
echo "----------------------------------------------------------------\n";
echo date('c') . "\n";
echo count($order_book['bids']) . " bids and " . count($order_book['asks']) . " asks\n";
echo sprintf("bid: %.8f ask: %.8f", $order_book['bids'][0][0], $order_book['asks'][0][0]) . "\n";
}
```
@@ -0,0 +1,180 @@
- [Bybit Updated](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
echo 'CCXT v' . \ccxt\Exchange::VERSION . "\n";
$exchange = new \ccxt\bybit(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET_KEY',
// 'verbose' => true, // uncomment if debug output is needed
));
// Example 1: Spot : fetch balance, create order, cancel it and check canceled orders
function example_1($exchange) {
$exchange->options['defaultType'] = 'spot'; // very important set spot as default type
$markets = $exchange->load_markets();
// fetch spot balance
$balance = $exchange->fetch_balance();
print_r($balance);
// create limit order
$symbol = 'LTC/USDT';
$type = 'limit';
$side = 'buy';
$amount = 0.1;
$price = 50;
$create_order = $exchange->create_order($symbol, $type, $side, $amount, $price);
print_r('Create order id:' . $create_order['id']);
// cancel created order
$canceled_order = $exchange->cancel_order($create_order['id'], $symbol);
print_r($canceled_order);
// Check canceled orders (bybit does not have a single endpoint to check orders
// we have to choose whether to check open or closed orders and call fetch_open_orders
// or fetch_closed_orders respectively
$orders = $exchange->fetch_closed_orders($symbol);
print_r($orders);
}
// -----------------------------------------------------------------------------------------
// Example 2 :: Swap : fetch balance, open a position and close it
function example_2($exchange) {
$exchange->options['defaultType'] = 'swap'; // very important set swap as default type
$markets = $exchange->load_markets();
// fetch swap balance
$balance = $exchange->fetch_balance();
print_r($balance);
// create market order and open position
$symbol = 'LTC/USDT:USDT';
$type = 'market';
$side = 'buy';
$amount = 0.1;
$price = null;
$create_order = $exchange->create_order($symbol, $type, $side, $amount, $price);
print_r('Create order id:' . $create_order['id']);
// check opened position
$symbols = [ $symbol ];
$positions = $exchange->fetch_positions($symbols);
print_r($positions);
// Close position by issuing a order in the opposite direction
$side = 'sell';
$params = array (
'reduce_only' => true
);
$close_position = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r($close_position);
}
// -----------------------------------------------------------------------------------------
// Example 3 :: USDC Swap : fetch balance, open a position and close it
function example_3($exchange) {
$exchange->options['defaultType'] = 'swap'; // very important set swap as default type
$markets = $exchange->load_markets();
// fetch USDC swap balance
// when no symbol is available we can show our intent
// of using USDC endpoints by either using defaultSettle in options or
// settle in params
// Using Options: exchange->$options['defaultSettle'] = 'USDC';
// Using params:
$balance_params = array(
'settle' => 'USDC'
);
$balance = $exchange->fetch_balance($balance_params);
print_r($balance);
// create order and open position
// taking into consideration that USDC markets do not support
// market orders
$symbol = 'BTC/USD:USDC';
$type = 'limit';
$side = 'buy';
$amount = 0.01;
$price = 20000; // adjust this accordingly
$create_order = $exchange->create_order($symbol, $type, $side, $amount, $price);
print_r('Create order id:' . $create_order['id']);
// check if the order was filled and the position opened
$symbols = [ $symbol ];
$positions = $exchange->fetch_positions($symbols);
print_r($positions);
// close position (assuming it was already opened) by issuing an order in the opposite direction
$side = 'sell';
$params = array (
'reduce_only' => true
);
$close_position = $exchange->create_order($symbol, $type, $side, $amount, $price, $params);
print_r($close_position);
}
// -----------------------------------------------------------------------------------------
// Example 3 :: Future : fetch balance, create stop-order and check open stop-orders
function example_4($exchange) {
$exchange->options['defaultType'] = 'future'; // very important set future as default type
$markets = $exchange->load_markets();
// fetch future balance
$balance = $exchange->fetch_balance();
print_r($balance);
// create stop-order
$symbol = 'ETH/USD:ETH-220930';
$type = 'limit';
$side = 'buy';
$amount = 10; // in USD for inverse futures
$price = 1200;
$stop_order_params = array(
'position_idx' => 0, // 0 One-Way Mode, 1 Buy-side, 2 Sell-side, default = 0
'stopPrice' => 1000, // mandatory for stop orders
'basePrice' => 1100 // mandatory for stop orders
);
$stop_order = $exchange->create_order($symbol, $type, $side, $amount, $price, $stop_order_params);
print_r('Create order id:' . $stop_order['id']);
// check opened stop-order
$open_order_params = array(
'stop' => true
);
$open_orders = $exchange->fetch_open_orders($symbol, null, null, $open_order_params);
print_r($open_orders);
// cancell all open stop-orders
$cancel_orders = $exchange->cancel_all_orders($symbol, $open_order_params);
print_r($cancel_orders);
}
// -----------------------------------------------------------------------------------------
function main($exchange) {
example_1($exchange);
example_2($exchange);
example_3($exchange);
example_4($exchange);
}
main($exchange)
?>
```
@@ -0,0 +1,32 @@
- [Bytetrade Create Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
echo 'PHP v' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION . "\n";
echo 'CCXT v' . \ccxt\Exchange::VERSION . "\n";
$exchange = new \ccxt\bytetrade(array(
// replace with your keys
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
));
$exchange->load_markets();
$exchange->verbose = true;
$symbol = 'BTC/USDT';
$type = 'limit';
$side = 'buy';
$amount = 0.000865;
$price = 11560;
$order = $exchange->create_order($symbol, $type, $side, $amount, $price);
print_r ($order);
```
@@ -0,0 +1,34 @@
- [Cache Exchange Instance Reuse](./examples/php/)
```php
<?php
error_reporting(E_ALL);
date_default_timezone_set('UTC');
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
function create_exchange($exchange_id, $config) {
$exchange_class = '\\ccxt\\' . $exchange_id;
$exchange = new $exchange_class($config);
$cache_location = "./cached_{$exchange_id}_data.json";
$start_time = microtime(true);
if (file_exists($cache_location)) {
$loaded_cache = json_decode(file_get_contents($cache_location), true);
$exchange->set_markets($loaded_cache['markets'], $loaded_cache['currencies']);
print("{$exchange_id} Loaded markets from cache in " . (microtime(true) - $start_time) . " seconds\n");
} else {
$markets = $exchange->load_markets();
file_put_contents($cache_location, json_encode(['markets'=>$markets, 'currencies'=>$exchange->currencies]));
print("{$exchange_id} Loaded fresh markets in " . (microtime(true) - $start_time) . " seconds\n");
}
return $exchange;
}
$exchange1 = create_exchange('bittrex', ['custom_id'=>'mybittrex1']);
print ($exchange1->fetch_trades('BTC/USDT')[0]);
```
@@ -0,0 +1,41 @@
- [Cancel Order](./examples/php/)
```php
<?php
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\binance(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
// 'verbose' => true,
));
try {
$symbol = 'XRP/BTC';
// if you want to find out your open orders, you can use the below code,
if ($exchange->has['fetchOpenOrders']) {
$open_orders = $exchange->fetchOpenOrders($symbol);
} else if ($exchange->has['fetchOrders']) {
$all_orders = $exchange->fetchOrders($symbol);
$open_orders = $exchange->filter_by($all_orders, 'status', 'open');
} else {
echo ($exchange->id . ' fetch(Open)Orders not supported yet');
}
// now, depending the $open_orders array, fill the below ID
$orderId = 'xxxxxxxx';
// to cancel multiple orders together asynchronously, see the "async-await-multiple.php" example file to adopt the code
$exchange->cancel_order($orderId, $symbol);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
```
+210
View File
@@ -0,0 +1,210 @@
- [Cli](./examples/php/)
```php
<?php
error_reporting(E_ALL);
date_default_timezone_set('UTC');
include './ccxt.php';
use React\Async;
date_default_timezone_set('UTC');
echo 'PHP v' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION . "\n";
echo 'CCXT version :' . \ccxt\async\Exchange::VERSION . "\n";
$main = function() use ($argv) {
if (count($argv) > 2) {
# first we filter the args
$verbose = count(array_filter($argv, function ($option) { return strstr($option, '--verbose') !== false; })) > 0;
$args = array_values(array_filter($argv, function ($option) { return strstr($option, '--verbose') === false; }));
$demo = count(array_filter($argv, function ($option) { return strstr($option, '--demo') !== false; })) > 0;
$args = array_values(array_filter($argv, function ($option) { return strstr($option, '--demo') === false; }));
$test = count(array_filter($args, function ($option) { return strstr($option, '--test') !== false || strstr($option, '--testnet') !== false || strstr($option, '--sandbox') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--test') === false && strstr($option, '--testnet') === false && strstr($option, '--sandbox') === false; }));
$debug = count(array_filter($args, function ($option) { return strstr($option, '--debug') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--debug') === false; }));
$spot = count(array_filter($args, function ($option) { return strstr($option, '--spot') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--spot') === false; }));
$no_keys = count(array_filter($args, function ($option) { return strstr($option, '--no-keys') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--no-keys') === false; }));
$swap = count(array_filter($args, function ($option) { return strstr($option, '--swap') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--swap') === false; }));
$future = count(array_filter($args, function ($option) { return strstr($option, '--future') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--future') === false; }));
$option = count(array_filter($args, function ($option) { return strstr($option, '--option') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--option') === false; }));
$new_updates = count(array_filter($args, function ($option) { return strstr($option, '--newUpdates') !== false; })) > 0;
$args = array_values(array_filter($args, function ($option) { return strstr($option, '--newUpdates') === false; }));
$id = $args[1];
$member = $args[2];
$args = array_slice($args, 3);
$exchange_found = in_array($id, \ccxt\async\Exchange::$exchanges);
if ($exchange_found) {
$keys_global = './keys.json';
$keys_local = './keys.local.json';
$keys_file = file_exists($keys_local) ? $keys_local : $keys_global;
$config = json_decode(file_get_contents($keys_file), true);
$settings = array_key_exists($id, $config) ? $config[$id] : array();
$config = array_merge($settings, array(
'verbose' => $verbose && $debug, // set to true for debugging
));
// instantiate the exchange by id
$exchange = null;
if (in_array($id, \ccxt\pro\Exchange::$exchanges)) {
$exchange = '\\ccxt\\pro\\' . $id;
} else {
$exchange = '\\ccxt\\async\\' . $id;
}
$exchange = new $exchange($config);
if ($spot) {
$exchange->options['defaultType'] = 'spot';
} else if ($swap) {
$exchange->options['defaultType'] = 'swap';
} else if ($future) {
$exchange->options['defaultType'] = 'future';
} else if ($option) {
$exchange->options['defaultType'] = 'option';
}
if ($new_updates) {
$exchange->newUpdates = true;
}
if ($test) {
$exchange->set_sandbox_mode(true);
} else if ($demo) {
$exchange->enable_demo_trading(true);
}
if (!$no_keys) {
// check auth keys in env var
foreach ($exchange->requiredCredentials as $credential => $is_required) {
if ($is_required && !$exchange->$credential ) {
$credential_var = strtoupper($id . '_' . $credential); // example: KRAKEN_SECRET
$credential_value = getenv($credential_var);
if ($credential_value) {
if (str_contains($credential_value, "---BEGIN")) {
$credential_value = str_replace('\n', "\n", $credential_value);
}
$exchange->$credential = $credential_value;
}
}
}
}
$args = array_map(function ($arg) {
global $exchange;
if ($arg[0] === '{' || $arg[0] === '[')
return json_decode($arg, true);
if ($arg === 'NULL' || $arg === 'null')
return null;
if (preg_match('/^[+-]?[0-9]+$/', $arg))
return intval ($arg);
if (preg_match('/^[.eE0-9+-]+$/', $arg))
return floatval ($arg);
if (preg_match('/^[0-9]{4}[-]?[0-9]{2}[-]?[0-9]{2}[T\s]?[0-9]{2}[:]?[0-9]{2}[:]?[0-9]{2}/', $arg))
return $exchange->parse8601($arg);
else
return $arg;
}, $args);
$markets_path = '.cache/' . $exchange->id . '-markets.json';
if (file_exists($markets_path)) {
$markets = json_decode(file_get_contents($markets_path), true);
$exchange->markets = $markets;
} else {
// yield $exchange->load_markets();
}
$exchange->verbose = $verbose;
echo $exchange->id . '->' . $member . '(' . @implode(', ', $args) . ")\n";
$is_ws_method = false;
if (mb_strpos($member, 'watch') !== false) {
$is_ws_method = true;
}
while (true) {
try {
$result = yield call_user_func_array(array($exchange, $member), $args);
echo print_r($result, true) . "\n";
if (!$is_ws_method) {
# make sure to exit with exit code zero here
exit(0);
}
} catch (\ccxt\NetworkError $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
exit(1);
} catch (\ccxt\ExchangeError $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
exit(1);
} catch (Exception $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
if (property_exists($exchange, $member)) {
echo print_r($exchange->$member, true) . "\n";
} else {
echo $exchange->id . '->' . $member . ": no such property\n";
}
exit(1);
}
}
} else {
echo 'Exchange ' . $id . " not found\n";
exit(1);
}
} else {
print_r('Usage: php -f ' . __FILE__ . " exchange_id member [args...]\n");
exit(1);
}
};
function teste() {
yield 0;
}
$promise = Async\coroutine($main);
Async\await($promise);
?>
```
@@ -0,0 +1,45 @@
- [Coinbase Fetch All Balances](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\coinbase(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
// 'verbose' => true, // uncomment for debugging
));
$exchange->load_markets();
// $exchange->verbose = true; // uncomment for debugging
$result = array();
$params = array();
$loop = true;
do {
$balance = $exchange->fetch_balance($params);
$pagination = $exchange->safe_value($balance['info'], 'pagination');
if ($pagination === null) {
$loop = false;
} else {
$next_starting_after = $exchange->safe_string ($pagination, 'next_starting_after');
if ($next_starting_after !== null) {
$params['starting_after'] = $next_starting_after;
} else {
$loop = false;
}
}
echo $exchange->iso8601($exchange->milliseconds()) . "\n";
$result = $exchange->deep_extend($result, $balance);
} while ($loop);
echo "======================================================================\n";
var_dump($result);
?>
```
@@ -0,0 +1,53 @@
- [Coinbasepro Cursor Pagination](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\coinbasepro(array(
'apiKey' => 'YOUR_API_KEY', // required for fetch_orders, fetch_my_trades
'secret' => 'YOUR_SECRET', // required for fetch_orders, fetch_my_trades
'password' => 'YOUR_PASSWORD', // required for fetch_orders, fetch_my_trades
// 'verbose' => true, // uncomment for debugging
));
$exchange->load_markets ();
// $exchange->verbose = true; // uncomment for debugging
$all_results = array();
$symbol = 'ETH/USD';
$since = null;
$limit = 100;
$params = array();
do {
// any of the following methods should work:
// $results = $exchange->fetch_orders($symbol, $since, $limit, $params);
// $results = $exchange->fetch_my_trades($symbol, $since, $limit, $params);
$results = $exchange->fetch_trades($symbol, $since, $limit, $params);
echo $exchange->iso8601($exchange->milliseconds());
echo ' fetched ' . count($results) . " results\n";
$all_results = array_merge ($all_results, $results);
if (count($results) > 0) {
$last = count($results) - 1;
echo ' last result ' . $results[$last]['id'] . ' ' . $results[$last]['datetime'] . "\n";
echo ' first result ' . $results[0]['id'] . ' ' . $results[0]['datetime'] . "\n";
} else {
break;
}
@$params['after'] = $exchange->last_response_headers['cb-after'][0];
// uncomment one of the following:
// } while (true); // fetch all results forever
} while (count($all_results) < 1000); // fetch up to 1000 results
echo "fetched " . count($all_results) . " results in total\n";
?>
```
@@ -0,0 +1,20 @@
- [Coinone Markets](./examples/php/)
```php
<?php
include './ccxt.php';
$exchange = new \ccxt\coinone(array(
// 'verbose' => true, // uncomment for verbose output
));
$markets = $exchange->load_markets();
var_dump($markets);
echo "\n" . $exchange->name . " supports " . count($markets) . " pairs\n";
?>
```
@@ -0,0 +1,61 @@
- [Compare Two Exchanges Capabilities](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$prefix = '-';
$exchange_1 = new \ccxt\async\okx();
$exchange_2 = new \ccxt\async\htx();
$keys_1 = is_array($exchange_1->has) ? array_keys($exchange_1->has) : array();
$keys_2 = is_array($exchange_2->has) ? array_keys($exchange_2->has) : array();
// check missing from exchange-1
var_dump('### checking missing functionalities from exchange-1:', $exchange_1->id);
for ($i = 0; $i < count($keys_2); $i++) {
$key = $keys_2[$i];
if ($exchange_2->has[$key]) {
if (!in_array($key, $keys_1)) {
var_dump($prefix, $key, 'does not exist in', $exchange_1->id, 'as opposed to', $exchange_2->id);
} elseif ($exchange_2->has[$key] !== $exchange_1->has[$key]) {
var_dump($prefix, $key, '> ', $exchange_1->id, ':', $exchange_1->has[$key], ',', $exchange_2->id, ':', $exchange_2->has[$key]);
}
}
}
// check missing from exchange-2
var_dump('### checking missing functionalities from exchange-2:', $exchange_2->id);
for ($i = 0; $i < count($keys_1); $i++) {
$key = $keys_1[$i];
if ($exchange_1->has[$key]) {
if (!in_array($key, $keys_2)) {
var_dump($prefix, $key, 'does not exist in', $exchange_2->id, 'as opposed to', $exchange_1->id);
} elseif ($exchange_1->has[$key] !== $exchange_2->has[$key]) {
var_dump($prefix, $key, '> ', $exchange_2->id, ':', $exchange_2->has[$key], ',', $exchange_1->id, ':', $exchange_1->has[$key]);
}
}
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,90 @@
- [Create Order Position With Takeprofit Stoploss](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
var_dump('CCXT Version:', $ccxt->version);
// ------------------------------------------------------------------------------
function example() {
// at this moment, only OKX support embedded stop-loss & take-profit orders in unified manner. other exchanges are being added actively and will be available soon.
return Async\async(function () {
$exchange = new \ccxt\async\okx(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
'password' => 'YOUR_API_PASSWORD',
));
$symbol = 'DOGE/USDT:USDT';
$side = 'buy'; // 'buy' | 'sell'
$order_type = 'limit'; // 'market' | 'limit'
$amount = 1; // how many contracts (see `market(symbol).contractSize` to find out coin portion per one contract)
Async\await($exchange->load_markets());
$market = $exchange->market($symbol);
$ticker = Async\await($exchange->fetch_ticker($symbol));
$last_price = $ticker['last'];
$ask_price = $ticker['ask'];
$bid_price = $ticker['bid'];
// if order_type is 'market', then price is not needed
$price = null;
// if order_type is 'limit', then set a price at your desired level
if ($order_type === 'limit') {
$price = ($side === 'buy') ? $bid_price * 0.95 : $ask_price * 1.05; // i.e. 5% from current price
}
// set trigger price for stop-loss/take-profit to 2% from current price
// (note, across different exchanges "trigger" price can be also mentioned with different synonyms, like "activation price", "stop price", "conditional price", etc. )
$stop_loss_trigger_price = ($order_type === 'market' ? $last_price : $price) * ($side === 'buy' ? 0.98 : 1.02);
$take_profit_trigger_price = ($order_type === 'market' ? $last_price : $price) * ($side === 'buy' ? 1.02 : 0.98);
// when symbol's price reaches your predefined "trigger price", stop-loss order would be activated as a "market order". but if you want it to be activated as a "limit order", then set a 'price' parameter for it
$params = array(
'stopLoss' => array(
'triggerPrice' => $stop_loss_trigger_price,
'price' => $stop_loss_trigger_price * 0.98,
),
'takeProfit' => array(
'triggerPrice' => $take_profit_trigger_price,
'price' => $take_profit_trigger_price * 0.98,
),
);
$position_amount = $market['contractSize'] * $amount;
$position_value = $position_amount * $last_price;
// log
var_dump('Going to open a position', 'for', $amount, 'contracts worth', $position_amount, $market['base'], '~', $position_value, $market['settle'], 'using', $side, $order_type, 'order (', ($order_type === 'limit' ? $exchange->price_to_precision($symbol, $price) : ''), '), using the following params:');
var_dump($params);
var_dump('-----------------------------------------------------------------------');
try {
$created_order = Async\await($exchange->create_order($symbol, $order_type, $side, $amount, $price, $params));
var_dump('Created an order', $created_order);
// Fetch all your open orders for this symbol
// - use 'fetchOpenOrders' or 'fetchOrders' and filter with 'open' status
// - note, that some exchanges might return one order object with embedded stoploss/takeprofit fields, while other exchanges might have separate stoploss/takeprofit order objects
$all_open_orders = Async\await($exchange->fetch_open_orders($symbol));
var_dump('Fetched all your orders for this symbol', $all_open_orders);
} catch(Exception $e) {
var_dump(((string) $e));
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,52 @@
- [Create Order Ws Example](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\pro\binance(array(
'apiKey' => 'MY_API_KEY',
'secret' => 'MY_SECRET',
));
$exchange->set_sandbox_mode(true);
$exchange->verbose = true; // uncomment for debugging purposes if necessary
// load markets
Async\await($exchange->load_markets());
$symbol = 'ETH/USDT';
$type = 'limit';
$side = 'buy';
$amount = 0.01;
$price = 1000;
$orders = [];
for ($i = 1; $i < 5; $i++) {
$response = Async\await($exchange->create_order_ws($symbol, $type, $side, $amount, $price));
$price += $i;
$orders[] = $response;
}
var_dump($orders);
}) ();
}
Async\await(example());
```
@@ -0,0 +1,52 @@
- [Create Orders Example](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\async\binance(array(
'apiKey' => 'MY_API_KEY',
'secret' => 'MY_SECRET',
));
$exchange->set_sandbox_mode(true);
Async\await($exchange->load_markets());
$exchange->verbose = true; // uncomment for debugging purposes if necessary
$orders = Async\await($exchange->create_orders([array(
'symbol' => 'LTC/USDT:USDT',
'type' => 'limit',
'side' => 'buy',
'amount' => 10,
'price' => 55,
), array(
'symbol' => 'ETH/USDT:USDT',
'type' => 'market',
'side' => 'buy',
'amount' => 0.5,
)]));
var_dump($orders);
}) ();
}
Async\await(example());
```
@@ -0,0 +1,61 @@
- [Create Trailing Amount Order](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\async\bingx(array(
'apiKey' => 'MY_API_KEY',
'secret' => 'MY_SECRET',
));
// exchange.setSandboxMode (true);
// exchange.verbose = true; // uncomment for debugging purposes if necessary
Async\await($exchange->load_markets());
$symbol = 'BTC/USDT:USDT';
$order_type = 'market';
$side = 'sell';
$amount = 0.0001;
$price = null;
$reduce_only = true;
$trailing_amount = 100;
// const trailingTriggerPrice = undefined; // not supported on all exchanges
$params = array(
'reduceOnly' => $reduce_only,
'trailingAmount' => $trailing_amount,
);
try {
$create_order = Async\await($exchange->create_order($symbol, $order_type, $side, $amount, $price, $params));
// Alternatively use the createTrailingAmountOrder method:
// const create_order = await exchange.createTrailingAmountOrder (symbol, order_type, side, amount, price, trailingAmount, trailingTriggerPrice, {
// 'reduceOnly': reduceOnly,
// });
var_dump($create_order);
} catch(Exception $e) {
var_dump(((string) $e));
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,61 @@
- [Create Trailing Percent Order](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\async\bingx(array(
'apiKey' => 'MY_API_KEY',
'secret' => 'MY_SECRET',
));
// exchange.setSandboxMode (true);
// exchange.verbose = true; // uncomment for debugging purposes if necessary
Async\await($exchange->load_markets());
$symbol = 'BTC/USDT:USDT';
$order_type = 'market';
$side = 'sell';
$amount = 0.0001;
$price = null;
$reduce_only = true;
$trailing_percent = 10;
// const trailingTriggerPrice = undefined; // not supported on all exchanges
$params = array(
'reduceOnly' => $reduce_only,
'trailingPercent' => $trailing_percent,
);
try {
$create_order = Async\await($exchange->create_order($symbol, $order_type, $side, $amount, $price, $params));
// Alternatively use the createTrailingAmountOrder method:
// const create_order = await exchange.createTrailingPercentOrder (symbol, order_type, side, amount, price, trailingPercent, trailingTriggerPrice, {
// 'reduceOnly': reduceOnly,
// });
var_dump($create_order);
} catch(Exception $e) {
var_dump(((string) $e));
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,56 @@
- [Error Handling Message](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\bittrex(array(
'apiKey' => 'foo',
'secret' => 'bar',
));
$message = null;
try {
$result = $exchange->fetch_balance ();
var_dump ($result);
// these catch-clauses are showing the proper way of handling the errors
} catch (\ccxt\AuthenticationError $e) {
// handle authentication error here
} catch (\ccxt\NetworkError $e) {
// your code to handle the network code and retries here
} catch (\ccxt\ExchangeError $e) {
// your code to handle an exchange error
} catch (Exception $e) {
// This is an example of how NOT TO DO error handling
// One should not rely on the message string contained in the exception
// If you want to access it, that might indicate a design error in your code.
// See: https://github.com/ccxt/ccxt/issues/3053
$message = $e->getMessage();
if (preg_match ('/[a-z]+\s+(\{.+\})$/iu', $e->getMessage(), $matches)) {
$message = $matches[1];
}
echo print_r ($message, true) . "\n";
}
?>
```
@@ -0,0 +1,65 @@
- [Exchange Properties](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchanges = \ccxt\Exchange::$exchanges;
function print_supported_exchanges () {
$exchanges = \ccxt\Exchange::$exchanges;
echo 'Supported exchanges: ', implode (', ', $exchanges), "\n";
}
if (count ($argv) > 2) {
$id = $argv[1];
$exchange_found = in_array ($id, $exchanges);
if ($exchange_found) {
echo 'Instantiating ', $id, ' exchange', "\n";
$symbol = $argv[2];
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $id;
$exchange = new $exchange(array(
// 'verbose' => true, // uncomment for debug output
// set custom headers if needed
// 'headers' => array(
// 'YOUR_HEADER' => 'YOUR_VALUE',
// ),
));
// load all markets from the exchange
$markets = $exchange->load_markets ();
// you can also set any of the exchange properties after instantiation
// $exchange->verbose = true;
$ticker = $exchange->fetch_ticker ($symbol);
// output a list of all market symbols
print_r ($ticker);
} else {
echo 'Exchange ', $id, ' not found', "\n";
print_supported_exchanges ();
}
} else {
echo 'Usage: php -f ', __FILE__, ' id symbol', "\n";
print_supported_exchanges ();
}
?>
```
@@ -0,0 +1,28 @@
- [Fetch Balance](./examples/php/)
```php
<?php
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\okx(array(
// 'verbose' => true, // for debugging
// 'timeout' => 30000,
"apiKey" => "YOUR_API_KEY",
"secret" => "YOUR_API_SECRET",
));
try {
// about balance, read docs at : https://github.com/ccxt/ccxt/wiki/Manual#balance-structure
$result = $exchange->fetch_balance ();
print_r ($result);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
```
@@ -0,0 +1,108 @@
- [Fetch First Ohlcv Timestamp](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// ###### Description ######
//
// This function tries to fetch the "listing time" of a symbol by fetching the earliest available bar in daily resolution.
// Top-tier exchanges also support fetching smaller timeframes (eg. 1 minute) even several years back, so for those exchanges you can also use `useMinuteTimeframe = true` argument to get the timestamp rounded to the earliest minute bar (instead of daily bar timestamp).
// See usage in the end of this file
function fetch_first_bar_timestamp($exchange, $symbol, $use_minute_timeframe = false) {
// set some constants
return Async\async(function () use ($exchange, $symbol, $use_minute_timeframe) {
$milliseconds_per_day = 86400000;
$minutes_per_day = 1440;
$minimum_timestamp = 1230768000000; // 2009-01-01 (bitcoin created year)
// get market features
$market = $exchange->market($symbol);
$market_type = $exchange->safe_string($market, 'type');
$features = $exchange->safe_dict($exchange->features, $market_type, array());
if ($market['subType'] !== null) {
$features = $exchange->safe_dict($features, $market['subType'], array());
}
$ohlcv = $exchange->safe_dict($features, 'fetchOHLCV');
if ($ohlcv === null) {
return null;
}
$limit = $exchange->safe_integer($ohlcv, 'limit');
$fetch_params = array(
'maxRetriesOnFailure' => 3,
);
// start loop
$current_since = $exchange->milliseconds() - $milliseconds_per_day * ($limit - 1);
$found_start_time = 0;
// eslint-disable-next-line
while (true) {
$current_since = max($current_since, $minimum_timestamp);
$daily_bars = Async\await($exchange->fetch_ohlcv($symbol, '1d', $current_since, $limit, $fetch_params));
if (count($daily_bars) <= 0) {
break; // if no days returned, then probably start date was passed
}
$first_ts = $daily_bars[0][0];
if ($first_ts === $found_start_time) {
// if the first timestamp is equal to the last-fetched timestamp, then break here, because some exchanges still return initial bar even if since is much ahead to listing time
break;
}
$found_start_time = $first_ts;
$current_since = $found_start_time - $milliseconds_per_day * ($limit - 1); // shift 'since' one step back
if (count($daily_bars) === 1) {
// in some cases, some exchanges might still return first bar of chart when endtime overlaps previous day
break;
}
}
// if minute resolution needed
if ($use_minute_timeframe) {
$max_iteration = ((int) ceil($minutes_per_day / $limit)) * 2;
$all_promises = [];
for ($i = 0; $i < $max_iteration; $i++) {
$current_since = $found_start_time - $milliseconds_per_day + $i * $limit * 60 * 1000; // shift one-duration back for more accuracy for different kind of exchanges, like OKX, where first daily bar is offset by one day, but minute bars present
$all_promises[] = $exchange->fetch_ohlcv($symbol, '1m', $current_since, $limit, $fetch_params);
}
$all_responses = Async\await(Promise\all($all_promises));
// find earliest bar
for ($i = 0; $i < count($all_responses); $i++) {
$response = $all_responses[$i];
if (count($response) > 0) {
$found_start_time = $response[0][0];
break;
}
}
}
return $found_start_time;
}) ();
}
// ###### Usage ######
$run_example = false; // set to true to run example
if ($run_example) {
$my_ex = new \ccxt\async\binance();
Async\await($my_ex->load_markets());
$symbol = 'TRUMP/USDT';
$earliest_timestamp = Async\await(fetch_first_bar_timestamp($my_ex, $symbol, true));
var_dump('- Earliest bar timestamp:', $earliest_timestamp, ', readable: ', $my_ex->iso8601($earliest_timestamp));
var_dump('- market.created value:', $my_ex->market($symbol)['created']);
}
```
@@ -0,0 +1,75 @@
- [Fetch Ohlcv Many Exchanges Continuosly](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// fetch and handle constinuosly
function fetch_ohlcv_continuously($exchange, $symbol) {
return Async\async(function () use ($exchange, $symbol) {
while (true) {
try {
$ohlcv = Async\await($exchange->fetch_ohlcv($symbol));
$ohlcv_length = count($ohlcv);
var_dump('Fetched ', $exchange->id, ' - ', $symbol, ' candles. last candle: ', $ohlcv[$ohlcv_length - 1]);
} catch(Exception $e) {
var_dump($e);
break;
}
}
}) ();
}
// start exchanges and fetch OHLCV loop
function start_exchange($exchange_name, $symbols) {
return Async\async(function () use ($exchange_name, $symbols) {
$exchange_class = '\ccxt\async\\'.$exchange_name;
$ex = new $exchange_class(array());
$promises = [];
for ($i = 0; $i < count($symbols); $i++) {
$symbol = $symbols[$i];
$promises[] = fetch_ohlcv_continuously($ex, $symbol);
}
Async\await(Promise\all($promises));
Async\await($ex->close());
}) ();
}
// main function
function example() {
return Async\async(function () {
$exchanges = ['binance', 'okx', 'kraken'];
$symbols = ['BTC/USDT', 'ETH/USDT'];
$promises = [];
for ($i = 0; $i < count($exchanges); $i++) {
$exchange_name = $exchanges[$i];
$promises[] = start_exchange($exchange_name, $symbols);
}
Async\await(Promise\all($promises));
}) ();
}
Async\await(example());
```
@@ -0,0 +1,44 @@
- [Fetch Ohlcv](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$myex = new \ccxt\async\okx(array());
$from_timestamp = $myex->milliseconds() - 86400 * 1000; // last 24 hrs
$ohlcv = Async\await($myex->fetch_ohlcv('BTC/USDT', '1m', $from_timestamp, 3, array(
'whatever' => 123,
)));
$length = count($ohlcv);
if ($length > 0) {
$last_price = $ohlcv[$length - 1][4];
var_dump('Fetched ', $length, ' candles for ', $myex->id, ': last close ', $last_price);
} else {
var_dump('No candles have been fetched');
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,95 @@
- [Fetch Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$id = 'livecoin'; // edit this line
// ----------------------------------------------------------------------------
// instantiate the exchange by id
$exchange_class = '\\ccxt\\' . $id;
$exchange = new $exchange_class(array(
// some exchanges may require additional API credentials
'apiKey' => 'YOUR_API_KEY', // edit this line
'secret' => 'YOUR_SECRET', // edit this line
// this is not required! uncomment only if you want to debug it
// 'verbose' => true,
));
// ----------------------------------------------------------------------------
if ($exchange->has['fetchOrder'] === false) {
echo $exchange->id . " does not support fetchOrder() yet\n";
exit();
} else if ($exchange->has['fetchOrder'] === 'emulated') {
echo $exchange->id . " fetchOrder() is 'emulated' and relies " .
"on the `.orders` cache as described in the Manual:\n" .
"https://github.com/ccxt/ccxt/wiki/Manual#orders-cache\n";
exit();
}
// ----------------------------------------------------------------------------
if ($exchange->has['fetchOrder'] === true) {
// this is the order id returned from by any of the order API methods
// createOrder(), fetchOrders(), fetchOpenOrders(), fetchClosedOrders()
$order_id = '45125111901'; // edit this line
// most of exchanges will not require the symbol argument, but some of
// the exchanges will require it, and it's safe to always pass the
// symbol argument to fetchOrder along with the order id
$symbol = 'ETH/BTC'; // edit this line
// these params are exchange-specific, most of exchanges don't require them
// some exchanges or methods may require this or that parameter in certain
// cases, consult the exchanges' API docs to get a list of all params
$params = array(
// 'param1' => 'value1', // uncomment and edit if necessary
// 'param2' => 'value2', // uncomment and edit if necessary
);
try {
$order = $exchange->fetch_order($order_id, $symbol, $params);
print_r($order);
} catch (\ccxt\NetworkError $e) {
// in case of a networking or a connectivity error instead of simply
// printing the error message here, the application should define
// the behavior or a recover-and-retry strategy, because networking
// errors are temporary and occasionally happen with all exchanges
// a retry after a while may be enough, depending on the error
echo get_class ($e) . ': ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
// in case of an exchange error the application should stop and signal
// the error to the developer or to the user, human interference is
// required to resolve an exchange error in each specific case
echo get_class($e) . ': ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
}
}
```
@@ -0,0 +1,45 @@
- [Fetch Ticker](./examples/php/)
```php
<?php
// ##########################################
// for asynchronous (async/await) version check: https://github.com/ccxt/ccxt/blob/master/examples/php/async-await.php
// ##########################################
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\okx(array(
// 'verbose' => true, // for debugging
'timeout' => 30000,
));
// If you want to use test-mode (a.k.a. sandbox), uncomment the following line:
// $exchange->set_sandbox_mode(true);
$symbol = 'ETH/USDT';
try {
if (array_key_exists($symbol, $exchange->markets)) {
$market = $exchange->market($symbol);
} else {
echo $exchange->id . ' does not have market symbol ' . $symbol . "; Supported symbols:\n";
echo print_r($exchange->symbols, true) . "\n";
exit();
}
if($market['active']) {
$result = $exchange->fetch_ticker($symbol);
echo "Ticker: " . $result['symbol'] . ', 24hr high: '. $result['high']. "\n";
} else {
echo $exchange->id . ' market ' . $symbol . " is not active!\n";
}
} catch (Exception $e) {
if ($e instanceof \ccxt\NetworkError) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} else {
echo '['. get_class($e) . '] ' . $e->getMessage() . "\n";
}
}
```
@@ -0,0 +1,46 @@
- [Fetch Tickers](./examples/php/)
```php
<?php
// ##########################################
// for asynchronous (async/await) version check: https://github.com/ccxt/ccxt/blob/master/examples/php/async-await.php
// ##########################################
include dirname(dirname(dirname(__FILE__))) . '/ccxt.php';
date_default_timezone_set('UTC');
$exchange =new \ccxt\binance(array(
// 'verbose' => true, // for debugging
'timeout' => 30000,
));
$markets = $exchange->load_markets();
try {
if ($exchange->has['fetchTickers']) {
// one API call for all tickers (preferred way)
$result = $exchange->fetch_tickers (); // note, don't call it for specifically binance more than once in every few seconds.
echo "Called fetchTickers() for all tickers at once. Results count: " . count($result) . "\n";
} else if ($exchange->has['fetchTicker']) {
// Individual API calls for all tickers one by one (non-preferred way)
echo "fetchTickers() is not supported by " . $exchange->id . ", calling individual fetchTicker() for each symbol instead.\n";
// fetch one by one (not recommended)
$i = 0;
$test_symbols_amount = 4;
foreach ($markets as $symbol => $m) {
if ($i++ && $i > $test_symbols_amount) {
echo "Stopping after getting " . $test_symbols_amount . " test symbols.\n";
break;
}
$result = $exchange->fetch_ticker($symbol);
echo "Fetched ticker for " . $result['symbol'] . ", 24hr high: " . $result['high'] . "\n";
}
} else {
echo "fetchTicker/s() not supported by " . $exchange->id . ", skipping.\n";
}
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
```
@@ -0,0 +1,54 @@
- [Gateio Futures](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\gateio(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET_KEY',
'options' => array(
'defaultType' => 'future',
),
// 'verbose' => true, // uncomment if debug output is needed
));
// Example 1: Creating future (market) order
try {
$markets = $exchange->load_markets ();
// find a future
$symbol = null;
foreach($markets as $key => $market) {
if ($market['future']) {
$symbol = $market['symbol']; // example BTC/USDT:USDT-22031
break;
}
}
if ($symbol != null) {
$type = 'market';
$side = 'buy';
$amount = 1;
// placing an order
$order = $exchange->create_order ($symbol, $type, $side, $amount);
var_dump ($order);
// listing open orders
$open_orders = $exchange->fetch_open_orders($symbol);
var_dump($open_orders);
}
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,91 @@
- [Gateio Swaps](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\gateio(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET_KEY',
'options' => array(
'defaultType' => 'swap',
),
// 'verbose' => true, // uncomment if debug output is needed
));
// Example 1: Creating and canceling a linear future (limit) order
try {
$markets = $exchange->load_markets ();
$symbol = 'LTC/USDT:USDT';
$type = 'limit';
$side = 'buy';
$amount = 1;
$price = 55;
// placing an order
$order = $exchange->create_order ($symbol, $type, $side, $amount, $price);
var_dump ($order);
// listing open orders
$open_orders = $exchange->fetch_open_orders($symbol);
var_dump($open_orders);
// cancel order
$cancel = $exchange->cancel_order ($order['id'], $symbol);
var_dump ($cancel);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
// Example 2: Creating and canceling a linear future (stop-limit) order with leverage
try {
$markets = $exchange->load_markets ();
$symbol = 'LTC/USDT:USDT';
$type = 'limit';
$side = 'buy';
$amount = 1;
$price = 55;
$stop_price = 130;
$params = array (
'stopPrice' => $stop_price,
);
// set leverage
$leverage = $exchange->set_leverage(3, $symbol);
var_dump($leverage);
// placing an order
$order = $exchange->create_order ($symbol, $type, $side, $amount, $price, $params);
var_dump ($order);
// listing open orders
$open_orders = $exchange->fetch_open_orders($symbol);
// var_dump($open_orders);
// cancel order
$cancelParams = array (
'isStop' => true,
);
$cancel = $exchange->cancel_order ($order['id'], $symbol, $cancelParams);
var_dump ($cancel);
// reset leverage
$leverage = $exchange->set_leverage(1, $symbol);
var_dump($leverage);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,32 @@
- [Huobi Fetch Balance](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\huobipro(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET',
// 'verbose' => true, // uncomment if debug output is needed
));
try {
$balance = $exchange->fetch_balance ();
var_dump ($balance);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,53 @@
- [Huobi Futures](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\huobipro(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET_KEY',
'options' => array(
'defaultType' => 'future',
)
// 'verbose' => true, // uncomment if debug output is needed
));
try {
$markets = $exchange->load_markets ();
// creating and canceling a linear swap (limit) order
$symbol = 'ADA/USD:ADA-220121'; // the last segment is the date of expiration (can be next week, next quarter, ...) adjust it accordingly
$order_type = 'limit';
$side = 'buy';
$offset = 'open';
$leverage = 1;
$amount = 1;
$price = 1;
$params = array (
'offset' => $offset,
'lever_rate' => $leverage,
);
$order = $exchange->create_order ($symbol, $order_type, $side, $amount, $price, $params);
var_dump ($order);
$cancel = $exchange->cancel_order ($order['id'], $symbol);
var_dump ($cancel);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,48 @@
- [Huobi Swaps](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\huobipro(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET_KEY',
// 'verbose' => true, // uncomment if debug output is needed
));
try {
$markets = $exchange->load_markets ();
// creating a linear swap (limit) order
$symbol = 'ADA/USDT:USDT';
$order_type = 'limit';
$side = 'buy';
$offset = 'open';
$leverage = 1;
$amount = 1;
$price = 1;
$params = array (
'offset' => $offset,
'lever_rate' => $leverage,
);
$order = $exchange->create_order ($symbol, $order_type, $side, $amount, $price, $params);
var_dump ($order['id']);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,68 @@
- [Indodax Fetch Balance Create Order Cancel Order](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchange = new \ccxt\indodax(array(
'apiKey' => 'YOUR_API_KEY', // ←------------ replace with your keys
'secret' => 'YOUR_SECRET',
));
//-----------------------------------------------------------------------------
// querying balance
$balance = $exchange->fetch_balance();
print_r($balance);
// do whatever you need here with your balance...
//-----------------------------------------------------------------------------
// placing and canceling orders
$symbol = 'BTC/IDR'; // bitcoin contract according to bitmex futures coding
$type = 'limit';
$side = 'sell'; // or 'buy'
$amount = 1.0;
$price = 6500.0; // or None
// extra params and overrides if necessary
$params = array(
// ...
);
// buying
$buy_order1 = $exchange->create_limit_buy_order($symbol, $amount, $price, $params);
echo "Buy order 1:\n";
print_r($buy_order1);
$buy_order2 = $exchange->create_order($symbol, $type, 'buy', $amount, $price, $params);
// order side hardcoded here ↑ for example
echo "Buy order 2:\n";
print_r($buy_order2);
// selling
$sell_order1 = $exchange->create_limit_sell_order($symbol, $amount, $price, $params);
echo "Sell order 1:\n";
print_r($sell_order1);
$sell_order2 = $exchange->create_order ($symbol, $type, $side, $amount, $price, $params);
// order side from a variable here ↑ for example
echo "Sell order 2:\n";
print_r($sell_order2);
// canceling
$exchange->cancel_order($buy_order1['id'], $symbol);
$exchange->cancel_order($buy_order2['id'], $symbol);
$exchange->cancel_order($sell_order1['id'], $symbol);
$exchange->cancel_order($sell_order2['id'], $symbol);
```
@@ -0,0 +1,77 @@
- [Kraken Create And Close Position](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
var_dump('CCXT Version:', $ccxt->version);
// ------------------------------------------------------------------------------
function example() {
return Async\async(function () {
$exchange = new \ccxt\async\kraken(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
));
$symbol = 'UNI/USD';
$side = 'buy'; // set it to 'buy' for a long position, 'sell' for a short position
$order_type = 'market'; // set it to 'market' or 'limit'
$amount = 1;
$leverage = 2;
Async\await($exchange->load_markets());
$market = $exchange->market($symbol);
// if order_type is 'market', then price is not needed
$price = null;
// if order_type is 'limit', then set a price at your desired level
// you can fetch the ticker and update price
// const ticker = await exchange.fetchTicker (symbol);
// const last_price = ticker['last'];
// const ask_price = ticker['ask'];
// const bid_price = ticker['bid'];
// if (order_type === 'limit') {
// price = (side === 'buy') ? bid_price * 0.95 : ask_price * 1.05; // i.e. 5% from current price
// }
$params = array(
'leverage' => $leverage,
);
// log
var_dump('Going to open a position', 'for', $amount, 'worth', $amount, $market['base'], '~', $market['settle'], 'using', $side, $order_type, 'order (', ($order_type === 'limit' ? $exchange->price_to_precision($symbol, $price) : ''), '), using the following params:');
var_dump($params);
var_dump('-----------------------------------------------------------------------');
try {
$created_order = Async\await($exchange->create_order($symbol, $order_type, $side, $amount, $price, $params));
var_dump('Created an order', $created_order);
// Fetch all your closed orders for this symbol (because we used market order)
// - use 'fetchClosedOrders' or 'fetchOrders' and filter with 'closed' status
$all_closed_orders = Async\await($exchange->fetch_closed_orders($symbol));
var_dump('Fetched all your closed orders for this symbol', $all_closed_orders);
$all_open_positions = Async\await($exchange->fetch_positions($symbol));
var_dump('Fetched all your positions for this symbol', $all_open_positions);
} catch(Exception $e) {
var_dump(((string) $e));
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,34 @@
- [Kraken Query Ledgers](./examples/php/)
```php
<?php
include './ccxt.php';
// include 'Console/Table.php';
date_default_timezone_set('UTC');
// instantiate the exchange by id
$exchange = '\\ccxt\\kraken';
$exchange = new $exchange(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET_KEY',
));
// get ledgers
$ledgers = $exchange->privatePostLedgers ();
// get ledger ids
$ids = array_keys ($ledgers['result']['ledger']);
// get ledger entries for ledger id
$ledger_entries = $exchange->privatePostQueryLedgers(array(
'id' => $ids[0],
));
var_dump ($ledger_entries);
?>
```
@@ -0,0 +1,93 @@
- [Kucoin Fetch All Deposit Addresses](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
echo 'PHP v' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION . "\n";
echo 'CCXT v' . \ccxt\Exchange::VERSION . "\n";
$exchange = new \ccxt\kucoin(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
'password' => 'YOUR_API_PASSWORD',
'options' => array(
'versions' => array(
'public' => array(
'GET' => array(
'currencies/{currency}' => 'v2',
),
),
),
),
));
$markets = $exchange->load_markets();
// $exchange->verbose = true; // uncomment for debugging purposes if necessary
function fetch_create_deposit_address_helper($exchange, $code, $chain = null) {
$response = null;
try {
$response = $exchange->fetch_deposit_address($code, $chain ? array('chain' => strtolower($chain)) : array());
if ((!$response['address']) || (!strlen($response['address']))) {
throw new \ccxt\ExchangeError ($exchange->id);
}
} catch (\ccxt\ExchangeError $e) {
$response = $exchange->create_deposit_address($code, $chain ? array('chain' => strtolower($chain)) : array());
}
return $response;
}
function fetch_create_deposit_address($exchange, $code, $chainName, $chain = null) {
try {
$response = fetch_create_deposit_address_helper($exchange, $code, $chain);
echo $code, ' has a ', $chainName, ' address ', $response['address'], ($response['tag'] && strlen($response['tag'])) ? ':' . $response['tag'] : '', "\n";
return $response;
} catch (\ccxt\ExchangeError $e) {
echo 'Failed to fetch or create ', $code, ' ', $chainName, ' address: ', $e->getMessage(), "\n";
}
}
$codes = array_keys($exchange->currencies);
$results = array();
foreach ($codes as $code) {
$response = $exchange->public_get_currencies_currency(array('currency' => $code));
$currency = $exchange->safe_value($response, 'data');
if ($currency) {
$chains = $exchange->safe_value($currency, 'chains');
if ((count($chains) > 1) && ($code !== 'BNB')) {
foreach ($chains as $chain) {
echo "\n\nhere", $code, "\n\n";
$chainName = $exchange->safe_string($chain, 'chainName');
$address = fetch_create_deposit_address($exchange, $code, $chainName, $chainName);
if (!isset($results[$code])) {
$results[$code] = array();
}
$results[$code][$chainName] = $address;
}
} else {
$chain = $exchange->safe_value($chains, 0);
$chainName = $exchange->safe_string($chain, 'chainName');
$address = fetch_create_deposit_address($exchange, $code, $chainName);
if (!isset($results[$code])) {
$results[$code] = array();
}
$results[$code][$chainName] = $address;
}
} else {
echo $code, ' has no addresses', "\n";
}
}
print_r($results);
```
@@ -0,0 +1,126 @@
- [Kucoin Implicit Inner Transfer V1](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$id = 'kucoin'; // edit this line
// ----------------------------------------------------------------------------
// instantiate the exchange by id
$exchange_class = '\\ccxt\\' . $id;
$exchange = new $exchange_class(array(
// some exchanges may require additional API credentials
'apiKey' => 'YOUR_API_KEY', // edit this line
'secret' => 'YOUR_SECRET', // edit this line
'password' => 'YOUR_APIKEY_PASSWORD', // edit this line
// this is not required! uncomment only if you want to debug it
// 'verbose' => true,
));
// ----------------------------------------------------------------------------
// https://docs.kucoin.com/#inner-transfer
// the difference between unified currency codes and exchange-specific
// currency ids is explained here: https://github.com/ccxt/ccxt/wiki/Manual#symbols-and-market-ids
$code = 'BTC'; // a unified currency code, edit this line
$from = 'main'; // or 'trade', edit this line
$to = 'trade'; // or 'main', edit this line
$amount = '0.123'; // edit this line
// ----------------------------------------------------------------------------
// load "from" and "to" accounts
function get_account_id($exchange, $type, $code) {
// load markets first
$exchange->load_markets(); // this will be executed only once
// convert from a common unified currency code to exchange-specific currency id
$currency_id = $exchange->currency_id($code);
echo "Loading a '" . $type . "' account for '" . $code . "'\n";
$accounts = $exchange->private_get_accounts(array(
'type' => $type,
));
$data = $exchange->safe_value($accounts, 'data', array());
$accounts_by_currency_id = $exchange->index_by($accounts['data'], 'currency');
$account_id = null;
if (!array_key_exists($currency_id, $accounts_by_currency_id)) {
echo "Could not find a '" . $type . "' account for '" . $code . "'\n";
echo "Trying to create a new '" . $type . "' account for '" . $code . "'\n";
try {
$response = $exchange->private_post_accounts(array(
'type' => $type,
'currency' => $currency_id
));
echo "Successfully created a new '" . $type . "' account for '" . $code . "'\n";
$account_id = $response['data']['id'];
} catch (Exception $e) {
echo "Failed to create a new '" . $type . "' account for '" . $code . "'\n";
echo get_class($e) . ': ' . $e->getMessage() . "\n";
exit();
}
} else {
$account_id = $accounts_by_currency_id[$currency_id]['id'];
}
echo "Successfully loaded a '" . $type . "' account for '" . $code . "': " . $account_id . "\n";
return $account_id;
}
// ----------------------------------------------------------------------------
$from_account_id = get_account_id($exchange, $from, $code); // payer (obtained through the "list account" interface)
$to_account_id = get_account_id($exchange, $to, $code); // receiver
echo "Transferring '" . $amount . "' '" . $code . "' from '" . $from . "' account '" . $from_account_id . "' to '" . $to . "' account '" . $to_account_id . "'\n";
// set the arguments for the implicit method
$params = array(
// set a unique identifier for this transfer
// can be any arbitrary string that has not been used yet
'clientOid' => $exchange->uuid(),
'payAccountId' => $from_account_id,
'recAccountId' => $to_account_id,
'amount' => $amount, // a string, transfer amount
);
try {
$response = $exchange->private_post_accounts_inner_transfer($params);
print_r($response);
} catch (Exception $e) {
echo get_class($e) . ': ' . $e->getMessage() . "\n";
}
```
@@ -0,0 +1,116 @@
- [Latoken Example](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$symbol = 'BTC/USDT';
$exchange_id = 'latoken';
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $exchange_id;
$exchange = new $exchange(array(
// 'verbose': true, // uncomment for debugging purposes
// uncomment and change for your keys to enable private calls
// 'apiKey': 'YOUR_API_KEY',
// 'secret': 'YOUR_API_SECRET',
));
$exchange->load_markets();
echo "-------------------------------------------------------------------\n";
echo $exchange->id, " has:\n";
var_dump($exchange->has);
// public API
echo "-------------------------------------------------------------------\n";
$markets = array_values($exchange->markets);
echo 'Loaded ', count($markets), ' ', $exchange->id, " markets:\n";
// var_dump($markets);
echo "-------------------------------------------------------------------\n";
$currencies = array_values($exchange->currencies);
echo 'Loaded ', count($currencies), ' ', $exchange->id, " currencies:\n";
// var_dump($currencies);
echo "-------------------------------------------------------------------\n";
$time = $exchange->fetch_time();
echo 'Exchange time: ', $exchange->iso8601($time), "\n";
echo "-------------------------------------------------------------------\n";
$ticker = $exchange->fetch_ticker($symbol);
var_dump($ticker);
echo "-------------------------------------------------------------------\n";
$tickers = $exchange->fetch_tickers();
echo 'Loaded ', count($tickers), ' ', $exchange->id, " tickers:\n";
// var_dump($tickers);
echo "-------------------------------------------------------------------\n";
$orderbook = $exchange->fetch_order_book ($symbol);
var_dump($orderbook);
echo "-------------------------------------------------------------------\n";
$trades = $exchange->fetch_trades($symbol);
var_dump(array_map(function ($x) use ($exchange) {
return $exchange->omit($x, array('info', 'timestamp'));
}, $trades));
echo "-------------------------------------------------------------------\n";
// private API
if ($exchange->check_required_credentials(false)) {
$balance = $exchange->fetch_balance();
var_dump($exchange->omit($balance, array('info')));
echo "-------------------------------------------------------------------\n";
$order = $exchange->create_order($symbol, 'limit', 'buy', 0.001, 10000);
var_dump($order);
echo "-------------------------------------------------------------------\n";
$open_orders = $exchange->fetch_open_orders($symbol);
var_dump($open_orders);
echo "-------------------------------------------------------------------\n";
$canceled = $exchange->cancel_order($order['id'], $order['symbol']);
var_dump($canceled);
echo "-------------------------------------------------------------------\n";
$closed_orders = $exchange->fetch_closed_orders($symbol);
var_dump($closed_orders);
echo "-------------------------------------------------------------------\n";
$canceled_orders = $exchange->fetch_canceled_orders($symbol);
var_dump($canceled_orders);
echo "-------------------------------------------------------------------\n";
$my_trades = $exchange->fetch_my_trades($symbol);
var_dump($my_trades);
}
?>
```
@@ -0,0 +1,62 @@
- [Load All At Once Async](./examples/php/)
```php
<?php
use Recoil\React\ReactKernel;
use Recoil\Recoil;
include './ccxt.php';
date_default_timezone_set('UTC');
function loadMarkets($exchange) {
try {
echo "Querying " . $exchange->id . "...\n";
$markets = yield $exchange->load_markets ();
$msg = count (array_values ($markets)) . " markets: " .
implode (', ', array_slice ($exchange->symbols, 0, 5)) . "...\n";
} catch (\ccxt\RequestTimeout $e) {
$msg = '[Timeout Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\DDoSProtection $e) {
$msg = '[DDoS Protection Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\AuthenticationError $e) {
$msg = '[Authentication Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\ExchangeNotAvailable $e) {
$msg = '[Exchange Not Available] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\NotSupported $e) {
$msg = '[Not Supported] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\NetworkError $e) {
$msg = '[Network Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\ExchangeError $e) {
$msg = '[Exchange Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (Exception $e) {
$msg = '[Error] ' . $e->getMessage() . "\n";
}
echo "--------------------------------------------\n";
echo $exchange->id . "\n";
echo $msg;
echo "\n";
}
$loop = \React\EventLoop\Factory::create();
$kernel = \Recoil\React\ReactKernel::create($loop);
$kernel->execute(function() use ($loop, $kernel) {
$exchanges = \ccxt\Exchange::$exchanges;
$yields = [];
foreach ($exchanges as $exchange) {
$id = "\\ccxt_async\\".$exchange;
$exchange = new $id(array('loop' => $loop, 'kernel' => $kernel));
$yields[] = loadMarkets($exchange);
}
yield $yields;
}, $loop);
$kernel->run();
```
@@ -0,0 +1,45 @@
- [Load All At Once](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
$exchanges = \ccxt\Exchange::$exchanges;
foreach ($exchanges as $exchange) {
$id = "\\ccxt\\".$exchange;
$exchange = new $id();
echo "--------------------------------------------\n";
echo $exchange->id . "\n";
try {
$markets = $exchange->load_markets ();
echo count (array_values ($exchange->markets)) . " markets: " .
implode (', ', array_slice ($exchange->symbols, 0, 5)) . "...\n";
} catch (\ccxt\RequestTimeout $e) {
echo '[Timeout Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\DDoSProtection $e) {
echo '[DDoS Protection Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\AuthenticationError $e) {
echo '[Authentication Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\ExchangeNotAvailable $e) {
echo '[Exchange Not Available] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\NotSupported $e) {
echo '[Not Supported] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . ' (ignoring)' . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
echo "\n";
}
?>
```
@@ -0,0 +1,115 @@
- [Margin Loan Borrow Buy Sell Repay](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// Note, this is just an example and might not yet work on other exchanges, which are being still unified.
function example() {
// ########## user inputs ##########
return Async\async(function () {
$exchange_class = '\ccxt\async\\'.'binance';
$exchange = new $exchange_class(array(
'apiKey' => 'xxx',
'secret' => 'xxx',
));
$symbol = 'BUSD/USDT'; // set target symbol
$margin_mode = 'isolated'; // margin mode (cross or isolated)
$collateral_coin = 'USDT'; // which asset you want to use for margin-borrow collateral
$borrow_coin = 'BUSD'; // which coin to borrow
$order_side = 'sell'; // which side to trade
$amount_to_trade = 14; // how many coins to sell
$order_type = 'limit'; // order type (can be market, limit or etc)
$limit_price = 0.99; // price to sell at (set undefined/null/None if market-order)
$margin_magnitude = 5; // target margin (aka 'leverage'). This might also be obtainable using other unified methods, but for example purposes, we set here manually
// ########## end of user-inputs ##########
//
// for example purposes, let's also check available balance at first
$balance_margin = Async\await($exchange->fetch_balance(array(
'defaultType' => 'margin',
'marginMode' => $margin_mode,
))); // use `defaultType` because of temporary bug, otherwise, after several days, you can use `type` too.
// if we don't have enought coins, then we have to borrow at first
$needed_amount_to_borrow = null; // will be auto-set below
if ($amount_to_trade > $balance_margin[$symbol][$borrow_coin]['free']) {
$needed_amount_to_borrow = $amount_to_trade - $balance_margin[$symbol][$borrow_coin]['free'];
var_dump('hmm, I have only ', $balance_margin[$symbol][$borrow_coin]['free'], ' ', $borrow_coin, ' in margin balance, and still need additional ', $needed_amount_to_borrow, ' to make an order. Lets borrow it.');
// To initate a borrow, at first, check if we have enough collateral (for this example, as we make a sell-short, we need '-1' to keep for collateral currency)
$needed_collateral_amount = $needed_amount_to_borrow / ($margin_magnitude - 1);
// Check if we have any collateral to get permission for borrow
if ($balance_margin[$symbol][$collateral_coin]['free'] < $needed_collateral_amount) {
// If we don't have enough collateral, then let's try to transfer collateral-asset from spot-balance to margin-balance
var_dump('hmm, I have only ', $balance_margin[$symbol][$collateral_coin]['free'], ' in balance, but ', $needed_collateral_amount, ' collateral is needed. I should transfer ', $needed_collateral_amount, ' from spot');
// let's check if we have spot balance at all
$balance_spot = Async\await($exchange->fetch_balance(array(
'type' => 'spot',
)));
if ($exchange->parse_number($balance_spot[$collateral_coin]['free']) < $needed_collateral_amount) {
var_dump('hmm, I neither do have enough balance on spot - only ', $balance_spot[$collateral_coin]['free'], '. Script can not continue...');
return;
} else {
var_dump('Transferring ', $needed_collateral_amount, ' to margin account');
Async\await($exchange->transfer($collateral_coin, $needed_collateral_amount, 'spot', $margin_mode, array(
'symbol' => $symbol,
)));
}
}
// now, as we have enough margin collateral, initiate borrow
var_dump('Initiating margin borrow of ', $needed_amount_to_borrow, ' ', $borrow_coin);
$borrow_result = Async\await($exchange->borrow_margin($borrow_coin, $needed_amount_to_borrow, $symbol, array(
'marginMode' => $margin_mode,
)));
}
var_dump('Submitting order.');
$order = Async\await($exchange->create_order($symbol, $order_type, $order_side, $amount_to_trade, $limit_price, array(
'marginMode' => $margin_mode,
)));
var_dump('Order was submitted !', $order['id']);
//
//
// ...
// ...
// some time later, if you want to repay the loan back (like 'close the position')...
// ...
// ...
//
//
// set the "repay-back" amount (for this example snippet, this will be same amount that we borrowed above)
if ($needed_amount_to_borrow !== null) {
$amount_to_repay_back = $needed_amount_to_borrow;
// At first, you need to get back the borrowed coin, by making an opposide trade
var_dump('Making purchase back of ', $amount_to_repay_back, ' ', $borrow_coin, ' to repay it back.');
$purchase_back_price = 1.01;
$order_back = Async\await($exchange->create_order($symbol, $order_type, ($order_side === 'buy' ? 'sell' : 'buy'), $amount_to_repay_back, $purchase_back_price, array(
'marginMode' => $margin_mode,
)));
var_dump('Now, repaying the loan.');
$repay_result = Async\await($exchange->repay_margin($borrow_coin, $amount_to_repay_back, $symbol, array(
'marginMode' => $margin_mode,
)));
var_dump('finished.');
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Method Overload Override](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// -----------------------------------------------------------------------------
// ###############################################
// ####### APPROACH 1: Overload the method #######
// ###############################################
function example_1() {
$ex = new \ccxt\kucoin();
$ex->add_method('fetch_ticker', function($symbol, $params = []) {
return 'hello from the overload method';
});
var_dump($ex->call_method('fetch_ticker', ['BTC/USDT']));
}
example_1();
// ###############################################
// ####### APPROACH 2: extend the class #######
// ###############################################
function example_2() {
$ex = new class extends \ccxt\kucoin {
public function fetch_ticker($symbol, $params = []) {
return 'Hello from the anonymous class!';
}
};
var_dump($ex->fetch_ticker('fetch_ticker', ['BTC/USDT']));
}
example_2();
```
@@ -0,0 +1,35 @@
- [Nonce Override](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
class MillisecondsNonceExchange extends \ccxt\yobit {
public function nonce() {
return $this->milliseconds();
}
}
$exchange = new MillisecondsNonceExchange(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_SECRET',
));
try {
$symbol = 'ETH/BTC';
$result = $exchange->fetch_balance($symbol);
var_dump ($result);
} catch (\ccxt\NetworkError $e) {
echo '[Network Error] ' . $e->getMessage() . "\n";
} catch (\ccxt\ExchangeError $e) {
echo '[Exchange Error] ' . $e->getMessage() . "\n";
} catch (Exception $e) {
echo '[Error] ' . $e->getMessage() . "\n";
}
?>
```
@@ -0,0 +1,19 @@
- [Order Book Level Depth Extra Param](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
// instantiate the exchange by id
$exchange = '\\ccxt\\kraken';
$exchange = new $exchange ();
$limit = 10; // up to ten order on each side, for example
var_dump ($exchange->fetch_order_book ('BTC/USD', $limit));
?>
```
@@ -0,0 +1,72 @@
- [Phemex Create Order Position With Takeprofit Stoploss](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// ------------------------------------------------------------------------------
function example() {
return Async\async(function () {
$exchange = new \ccxt\async\phemex(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
));
$symbol = 'XRP/USDT:USDT';
$side = 'buy'; // set it to 'buy' for a long position, 'sell' for a short position
$order_type = 'limit'; // set it to 'market' or 'limit'
$amount = 1; // how many contracts
$price = 0.5; // set a price at your desired level
// take profit and stop loss prices and types
$take_profit_trigger_price = 0.6;
$stop_loss_trigger_price = 0.4;
$take_profit_limit_price = 0.7;
$stop_loss_limit_price = 0.3;
Async\await($exchange->load_markets());
// when symbol's price reaches your predefined "trigger price", stop-loss order would be activated as a "market order". but if you want it to be activated as a "limit order", then set a 'price' parameter for it
$params = array(
'posSide' => 'Long',
'stopLoss' => array(
'triggerPrice' => $stop_loss_trigger_price,
'type' => 'limit',
'price' => $stop_loss_limit_price,
),
'takeProfit' => array(
'triggerPrice' => $take_profit_trigger_price,
'type' => 'limit',
'price' => $take_profit_limit_price,
),
);
var_dump('-----------------------------------------------------------------------');
try {
$created_order = Async\await($exchange->create_order($symbol, $order_type, $side, $amount, $price, $params));
var_dump('Created an order', $created_order);
// Fetch all your open orders for this symbol
$all_open_orders = Async\await($exchange->fetch_open_orders($symbol));
var_dump('Fetched all your orders for this symbol', $all_open_orders);
} catch(Exception $e) {
var_dump(((string) $e));
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,77 @@
- [Proxy Usage](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// 1) ABOUT CCXT PROXIES, READ MORE AT: https://docs.ccxt.com/#/README?id=proxy
// 2) in python, uncomment the below:
// if sys.platform == 'win32':
// asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
function example_proxy_url() {
return Async\async(function () {
$my_ex = new \ccxt\async\kucoin();
$my_ex->proxy_url = 'http://188.245.226.105:8090/proxy_url.php?caller=https://ccxt.com&url=';
var_dump(Async\await($my_ex->fetch('https://api.ipify.org/')));
}) ();
}
function example_http_proxy() {
return Async\async(function () {
$my_ex = new \ccxt\async\kucoin();
$my_ex->http_proxy = 'http://188.245.226.105:8911'; // "httpProxy" or "httpsProxy" (depending on your proxy protocol)
var_dump(Async\await($my_ex->fetch('https://api.ipify.org/')));
}) ();
}
function example_socks_proxy() {
return Async\async(function () {
$my_ex = new \ccxt\async\kucoin();
$my_ex->socks_proxy = 'socks5://127.0.0.1:1080'; // from protocols: socks, socks5, socks5h
var_dump(Async\await($my_ex->fetch('https://api.ipify.org/')));
}) ();
}
function example_web_sockets() {
return Async\async(function () {
$my_ex = new \ccxt\pro\kucoin();
$my_ex->http_proxy = 'http://188.245.226.105:8911'; // even though you are using WebSockets, you might also need to set up proxy for the exchange's REST requests
$my_ex->ws_proxy = 'http://188.245.226.105:8911'; // "wsProxy" or "wssProxy" or "wsSocksProxy" (depending on your proxy protocol)
Async\await($my_ex->load_markets());
//
// To ensure your WS proxy works, uncomment below code and watch the log
//
// myEx.verbose = true;
// await myEx.loadHttpProxyAgent ();
// await myEx.watch ('ws://188.245.226.105:9876/', 'myip'); // in the incoming logs, confirm that you see the proxy IP in "hello" message
//
var_dump(Async\await($my_ex->watch_ticker('BTC/USDT')));
Async\await($my_ex->close());
}) ();
}
// await example_proxyUrl ();
Async\await(example_http_proxy());
```
@@ -0,0 +1,34 @@
- [React Eventloop With Rate Limiting](./examples/php/)
```php
<?php
require dirname(__FILE__).'/../vendor/autoload.php';
include dirname(__FILE__) ."/../vendor/ccxt/ccxt/ccxt.php";
date_default_timezone_set('UTC');
use TomWright\Database\ExtendedPDO\ExtendedPDO as ExtendedPDO;
use TomWright\Database\QueryBuilder\SqlQueryBuilder as SqlQueryBuilder;
$loop = React\EventLoop\Factory::create ();
// instantiate the exchange by id
$exchange = '\\ccxt\\poloniex';
$exchange = new $exchange ();
$tick_function = function () use ($exchange, $loop, &$tick_function) {
global $exchange, $loop;
$order_book = $exchange->fetch_order_book ($symbol);
echo "----------------------------------------------------------------\n";
echo date ('c') . "\n";
echo count ($order_book['bids']) . " bids and " . count ($order_book['asks']) . " asks\n";
echo sprintf ("bid: %.8f ask: %.8f", $order_book['bids'][0][0], $order_book['asks'][0][0]) . "\n";
$loop->futureTick ($tick_function);
};
$loop->futureTick ($tick_function);
$loop->run ();
```
@@ -0,0 +1,77 @@
- [Sample Local Proxy Server With Cors](./examples/php/)
```php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Note, you are advised to whitelist your IP address if you are going to use such sample proxy script.
// Then, you can run this script against any target url, like:
// http://your_server.com/sample-proxy.php?url=https://api64.ipify.org/
class SampleProxy {
private $whitelisted_ips = [
'localhost',
'127.0.0.1',
'::1',
// if you are accessing this script from remote device, add your ip here
];
// helper function
private function enable_cors() {
// copied from https://stackoverflow.com/a/9866124/2377343
if (isset($_SERVER['HTTP_ORIGIN'])) { // Allow from any origin
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
}
public function fetch_url ($url, $post_options = []) {
// todo: POST method is not implemented in this example
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,0);
curl_setopt($ch, CURLOPT_HEADER ,0); // DO NOT RETURN HTTP HEADERS
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 9);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 9);
curl_setopt($ch, CURLOPT_ENCODING, '');
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public function __construct() {
if (!in_array($_SERVER['REMOTE_ADDR'], $this->whitelisted_ips)) {
die("Your IP is forbidden... " . strval($_SERVER['REMOTE_ADDR']));
}
$this->enable_cors();
echo $this->fetch_url(filter_var($_GET['url'], FILTER_SANITIZE_URL));
exit(0);
}
}
new SampleProxy();
```
@@ -0,0 +1,58 @@
- [Shared Markets](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
// ----------------------------------------------------------------------------
// an example of how to load markets for each exchange just once
// in order to save memory and time for initializing multiple exchange instances
// see these issues for details:
// - https://github.com/ccxt/ccxt/issues/7312
// - https://github.com/ccxt/ccxt/issues/8176
// ----------------------------------------------------------------------------
$keys = array(
'ids',
'markets',
'markets_by_id',
'currencies',
'currencies_by_id',
'base_currencies',
'quote_currencies',
'symbols',
);
$id = 'kraken';
$exchange_class = "\\ccxt\\{$id}";
$exchange = new $exchange_class();
$markets_on_disk = "./{$id}.markets.json";
$exchange->verbose = true; // this is a debug output to demonstrate which networking calls are being issued
if (file_exists($markets_on_disk)) {
$cache = json_decode(file_get_contents($markets_on_disk), true);
foreach ($keys as $key) {
$exchange->{$key} = $cache[$key];
}
} else {
$exchange->load_markets();
$cache = array();
foreach ($keys as $key) {
$cache[$key] = $exchange->{$key};
}
file_put_contents($markets_on_disk, json_encode($cache));
}
$exchange->fetch_ticker('ETH/BTC');
```
+87
View File
@@ -0,0 +1,87 @@
- [Symbols](./examples/php/)
```php
<?php
include './ccxt.php';
include 'Console/Table.php';
date_default_timezone_set('UTC');
function style ($s, $style) { return $style . $s . "\033[0m"; }
function green ($s) { return style ($s, "\033[92m"); }
function blue ($s) { return style ($s, "\033[94m"); }
function yellow ($s) { return style ($s, "\033[93m"); }
function red ($s) { return style ($s, "\033[91m"); }
function pink ($s) { return style ($s, "\033[95m"); }
function bold ($s) { return style ($s, "\033[1m"); }
function underline ($s) { return style ($s, "\033[4m"); }
function dump ($s) { echo implode (' ', func_get_args ()) . "\n"; }
$exchanges = \ccxt\Exchange::$exchanges;
function print_supported_exchanges () {
$exchanges = \ccxt\Exchange::$exchanges;
dump ('Supported exchanges:', green (implode (', ', $exchanges)));
}
function tabulate ($headers, $rows) {
$tbl = new Console_Table();
$tbl->setHeaders ($headers);
$tbl->addData ($rows);
return $tbl->getTable ();
}
function market_table_helper ($market) {
return array (
$market['id'],
$market['symbol'],
$market['base'],
$market['quote'],
$market['taker'],
$market['maker'],
json_encode ($market['precision']),
json_encode ($market['limits']),
);
}
if (count ($argv) > 1) {
$id = $argv[1];
$exchange_found = in_array ($id, $exchanges);
if ($exchange_found) {
dump ('Instantiating', green ($id), 'exchange');
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $id;
$exchange = new $exchange ();
// load all markets from the exchange
$markets = $exchange->load_markets ();
// output a list of all market symbols
dump (green ($id), 'has', count ($exchange->symbols), 'symbols:', yellow (implode (', ', $exchange->symbols)));
// output a table of all markets
@dump (tabulate(array('id', 'symbol', 'base', 'quote', 'taker', 'maker', 'precision', 'limits'), array_map ('market_table_helper', $markets)));
} else {
dump ('Exchange', red ($id), 'not found');
print_supported_exchanges ();
}
} else {
dump ('Usage: php -f', __FILE__, green ('id'));
print_supported_exchanges ();
}
?>
```
@@ -0,0 +1,33 @@
- [Trading View](./examples/php/)
```php
<?php
include './ccxt.php';
date_default_timezone_set('UTC');
// this example shows how to convert from CCXT OHLCV format to TradingView format
// and back from TradingView to OHLCV for various charting purposes/applications
$id = 'bittrex';
$symbol = 'ETH/BTC';
// instantiate the exchange by id
$exchange = '\\ccxt\\' . $id;
$exchange = new $exchange();
// OHLCV format by default
$ohlcv = $exchange->fetch_ohlcv($symbol);
// convert OHLCV → TradingView
$trading_view = $exchange->convert_ohlcv_to_trading_view($ohlcv);
// convert TradingView → OHCLV
$restored_ohlcvs = $exchange->convert_trading_view_to_ohlcv($trading_view);
print_r($restored_ohlcvs);
?>
```
@@ -0,0 +1,38 @@
- [Watch Ohlcv For Symbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$subscriptions = [['BTC/USDT', '5m'], ['ETH/USDT', '5m'], ['BTC/USDT', '1h']];
while (true) {
$ohlcv = Async\await($binance->watch_ohlcv_for_symbols($subscriptions));
var_dump($ohlcv);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,39 @@
- [Watch Ohlcv](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbol = 'BTC/USDT';
$timeframe = '1m';
while (true) {
$ohlcv = Async\await($binance->watch_ohlcv($symbol, $timeframe));
var_dump($ohlcv);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watch Orderbook For Symbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbols = ['BTC/USDT', 'ETH/USDT', 'DOGE/USDT'];
while (true) {
$orderbook = Async\await($binance->watch_order_book_for_symbols($symbols));
var_dump($orderbook['symbol'], $orderbook['asks'][0], $orderbook['bids'][0]);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watch Trades For Symbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbols = ['BTC/USDT', 'ETH/USDT', 'DOGE/USDT'];
while (true) {
$trades = Async\await($binance->watch_trades_for_symbols($symbols));
var_dump($trades);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watch Tickers](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbols = ['BTC/USDT', 'ETH/USDT', 'DOGE/USDT'];
while (true) {
$tickers = Async\await($binance->watch_tickers($symbols));
var_dump($tickers['BTC/USDT'], $tickers['ETH/USDT'], $tickers['DOGE/USDT']);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watchohlcvforsymbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$subscriptions = [['BTC/USDT', '5m'], ['ETH/USDT', '5m'], ['BTC/USDT', '1h']];
while (true) {
$ohlcv = Async\await($binance->watch_ohlcv_for_symbols($subscriptions));
var_dump($ohlcv);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watchorderbookforsymbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbol = ['BTC/USDT', 'ETH/USDT', 'DOGE/USDT'];
while (true) {
$orderbook = Async\await($binance->watch_order_book_for_symbols($symbol));
var_dump($orderbook['symbol'], $orderbook['asks'][0], $orderbook['bids'][0]);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,85 @@
- [Watchpositions Many Exchanges Continuosly](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
// watch and handle constinuosly
function watch_positions_continuously($exchange) {
return Async\async(function () use ($exchange) {
while (true) {
try {
$positions = Async\await($exchange->watch_positions());
var_dump('Fetched ', $exchange->id, ' - Positions: ', $positions);
} catch(Exception $e) {
var_dump($e);
break;
}
}
}) ();
}
// start exchanges and fetch OHLCV loop
function start_exchange($exchange_name, $config) {
return Async\async(function () use ($exchange_name, $config) {
$exchange_class = '\ccxt\async\\'.$exchange_name;
$ex = new $exchange_class($config);
$promises = [];
$promises[] = watch_positions_continuously($ex);
Async\await(Promise\all($promises));
Async\await($ex->close());
}) ();
}
// main function
function example() {
return Async\async(function () {
$exchanges = array(
'binanceusdm' => array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
),
'okx' => array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
),
'huobi' => array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
),
);
$promises = [];
$exchange_ids = is_array($exchanges) ? array_keys($exchanges) : array();
for ($i = 0; $i < count($exchange_ids); $i++) {
$exchange_name = $exchange_ids[$i];
$config = $exchanges[$exchange_name];
$promises[] = start_exchange($exchange_name, $config);
}
Async\await(Promise\all($promises));
}) ();
}
Async\await(example());
```
@@ -0,0 +1,40 @@
- [Watchpositions](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\pro\binanceusdm(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'YOUR_API_SECRET',
));
while (true) {
$trades = Async\await($exchange->watch_positions());
var_dump($trades);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,41 @@
- [Watchpositionsforsymbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$exchange = new \ccxt\pro\binanceusdm(array(
'apiKey' => 'YOUR_API_KEY',
'secret' => 'Your_API_SECRET',
));
$symbols = ['BTC/USDT:USDT', 'ETH/USDT:USDT', 'DOGE/USDT:USDT'];
while (true) {
$trades = Async\await($exchange->watch_positions($symbols));
var_dump($trades);
}
}) ();
}
Async\await(example());
```
@@ -0,0 +1,38 @@
- [Watchtradesforsymbols](./examples/php/)
```php
<?php
namespace ccxt;
include_once (__DIR__.'/../../ccxt.php');
// ----------------------------------------------------------------------------
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// -----------------------------------------------------------------------------
error_reporting(E_ALL);
date_default_timezone_set('UTC');
use ccxt\Precise;
use React\Async;
use React\Promise;
// AUTO-TRANSPILE //
function example() {
return Async\async(function () {
$binance = new \ccxt\pro\binance(array());
$symbols = ['BTC/USDT', 'ETH/USDT', 'DOGE/USDT'];
while (true) {
$trades = Async\await($binance->watch_trades_for_symbols($symbols));
var_dump($trades);
}
}) ();
}
Async\await(example());
```